libipt-sys 0.1.1

raw bindings to the libipt intel processor tracing library
Documentation
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
/*
 * Copyright (c) 2013-2019, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of Intel Corporation nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#if defined(FEATURE_ELF)
# include "load_elf.h"
#endif /* defined(FEATURE_ELF) */

#include "pt_cpu.h"
#include "pt_version.h"

#include "intel-pt.h"

#if defined(FEATURE_SIDEBAND)
#  include "libipt-sb.h"
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>

#include <xed-interface.h>


/* The type of decoder to be used. */
enum ptxed_decoder_type {
	pdt_insn_decoder,
	pdt_block_decoder
};

/* The decoder to use. */
struct ptxed_decoder {
	/* The decoder type. */
	enum ptxed_decoder_type type;

	/* The actual decoder. */
	union {
		/* If @type == pdt_insn_decoder */
		struct pt_insn_decoder *insn;

		/* If @type == pdt_block_decoder */
		struct pt_block_decoder *block;
	} variant;

	/* Decoder-specific configuration.
	 *
	 * We use a set of structs to store the configuration for multiple
	 * decoders.
	 *
	 * - block decoder.
	 */
	struct {
		/* A collection of decoder-specific flags. */
		struct pt_conf_flags flags;
	} block;

	/* - instruction flow decoder. */
	struct {
		/* A collection of decoder-specific flags. */
		struct pt_conf_flags flags;
	} insn;


	/* The image section cache. */
	struct pt_image_section_cache *iscache;

#if defined(FEATURE_SIDEBAND)
	/* The sideband session. */
	struct pt_sb_session *session;

#if defined(FEATURE_PEVENT)
	/* The perf event sideband decoder configuration. */
	struct pt_sb_pevent_config pevent;
#endif /* defined(FEATURE_PEVENT) */
#endif /* defined(FEATURE_SIDEBAND) */
};

/* A collection of options. */
struct ptxed_options {
#if defined(FEATURE_SIDEBAND)
	/* Sideband dump flags. */
	uint32_t sb_dump_flags;
#endif
	/* Do not print the instruction. */
	uint32_t dont_print_insn:1;

	/* Remain as quiet as possible - excluding error messages. */
	uint32_t quiet:1;

	/* Print statistics (overrides quiet). */
	uint32_t print_stats:1;

	/* Print information about section loads and unloads. */
	uint32_t track_image:1;

	/* Track blocks in the output.
	 *
	 * This only applies to the block decoder.
	 */
	uint32_t track_blocks:1;

	/* Print in AT&T format. */
	uint32_t att_format:1;

	/* Print the offset into the trace file. */
	uint32_t print_offset:1;

	/* Print the current timestamp. */
	uint32_t print_time:1;

	/* Print the raw bytes for an insn. */
	uint32_t print_raw_insn:1;

	/* Perform checks. */
	uint32_t check:1;

	/* Print the time stamp of events. */
	uint32_t print_event_time:1;

	/* Print the ip of events. */
	uint32_t print_event_ip:1;

#if defined(FEATURE_SIDEBAND)
	/* Print sideband warnings. */
	uint32_t print_sb_warnings:1;
#endif
};

/* A collection of flags selecting which stats to collect/print. */
enum ptxed_stats_flag {
	/* Collect number of instructions. */
	ptxed_stat_insn		= (1 << 0),

	/* Collect number of blocks. */
	ptxed_stat_blocks	= (1 << 1)
};

/* A collection of statistics. */
struct ptxed_stats {
	/* The number of instructions. */
	uint64_t insn;

	/* The number of blocks.
	 *
	 * This only applies to the block decoder.
	 */
	uint64_t blocks;

	/* A collection of flags saying which statistics to collect/print. */
	uint32_t flags;
};

static int ptxed_have_decoder(const struct ptxed_decoder *decoder)
{
	/* It suffices to check for one decoder in the variant union. */
	return decoder && decoder->variant.insn;
}

static int ptxed_init_decoder(struct ptxed_decoder *decoder)
{
	if (!decoder)
		return -pte_internal;

	memset(decoder, 0, sizeof(*decoder));
	decoder->type = pdt_block_decoder;

	decoder->iscache = pt_iscache_alloc(NULL);
	if (!decoder->iscache)
		return -pte_nomem;

#if defined(FEATURE_SIDEBAND)
	decoder->session = pt_sb_alloc(decoder->iscache);
	if (!decoder->session) {
		pt_iscache_free(decoder->iscache);
		return -pte_nomem;
	}

#if defined(FEATURE_PEVENT)
	memset(&decoder->pevent, 0, sizeof(decoder->pevent));
	decoder->pevent.size = sizeof(decoder->pevent);
	decoder->pevent.kernel_start = UINT64_MAX;
	decoder->pevent.time_mult = 1;
#endif /* defined(FEATURE_PEVENT) */
#endif /* defined(FEATURE_SIDEBAND) */

	return 0;
}

static void ptxed_free_decoder(struct ptxed_decoder *decoder)
{
	if (!decoder)
		return;

	switch (decoder->type) {
	case pdt_insn_decoder:
		pt_insn_free_decoder(decoder->variant.insn);
		break;

	case pdt_block_decoder:
		pt_blk_free_decoder(decoder->variant.block);
		break;
	}

#if defined(FEATURE_SIDEBAND)
	pt_sb_free(decoder->session);
#endif

	pt_iscache_free(decoder->iscache);
}

static void help(const char *name)
{
	printf("usage: %s [<options>]\n\n", name);
	printf("options:\n");
	printf("  --help|-h                            this text.\n");
	printf("  --version                            display version information and exit.\n");
	printf("  --att                                print instructions in att format.\n");
	printf("  --no-inst                            do not print instructions (only addresses).\n");
	printf("  --quiet|-q                           do not print anything (except errors).\n");
	printf("  --offset                             print the offset into the trace file.\n");
	printf("  --time                               print the current timestamp.\n");
	printf("  --raw-insn                           print the raw bytes of each instruction.\n");
	printf("  --check                              perform checks (expensive).\n");
	printf("  --iscache-limit <size>               set the image section cache limit to <size> bytes.\n");
	printf("  --event:time                         print the tsc for events if available.\n");
	printf("  --event:ip                           print the ip of events if available.\n");
	printf("  --event:tick                         request tick events.\n");
	printf("  --filter:addr<n>_cfg <cfg>           set IA32_RTIT_CTL.ADDRn_CFG to <cfg>.\n");
	printf("  --filter:addr<n>_a <base>            set IA32_RTIT_ADDRn_A to <base>.\n");
	printf("  --filter:addr<n>_b <limit>           set IA32_RTIT_ADDRn_B to <limit>.\n");
	printf("  --stat                               print statistics (even when quiet).\n");
	printf("                                       collects all statistics unless one or more are selected.\n");
	printf("  --stat:insn                          collect number of instructions.\n");
	printf("  --stat:blocks                        collect number of blocks.\n");
#if defined(FEATURE_SIDEBAND)
	printf("  --sb:compact | --sb                  show sideband records in compact format.\n");
	printf("  --sb:verbose                         show sideband records in verbose format.\n");
	printf("  --sb:filename                        show the filename on sideband records.\n");
	printf("  --sb:offset                          show the offset on sideband records.\n");
	printf("  --sb:time                            show the time on sideband records.\n");
	printf("  --sb:switch                          print the new image name on context switches.\n");
	printf("  --sb:warn                            show sideband warnings.\n");
#if defined(FEATURE_PEVENT)
	printf("  --pevent:primary/secondary <file>[:<from>[-<to>]]\n");
	printf("                              load a perf_event sideband stream from <file>.\n");
	printf("                              an optional offset or range can be given.\n");
	printf("  --pevent:sample-type <val>  set perf_event_attr.sample_type to <val> (default: 0).\n");
	printf("  --pevent:time-zero <val>    set perf_event_mmap_page.time_zero to <val> (default: 0).\n");
	printf("  --pevent:time-shift <val>   set perf_event_mmap_page.time_shift to <val> (default: 0).\n");
	printf("  --pevent:time-mult <val>    set perf_event_mmap_page.time_mult to <val> (default: 1).\n");
	printf("  --pevent:tsc-offset <val>   show perf events <val> ticks earlier.\n");
	printf("  --pevent:kernel-start <val> the start address of the kernel.\n");
	printf("  --pevent:sysroot <path>     prepend <path> to sideband filenames.\n");
#if defined(FEATURE_ELF)
	printf("  --pevent:kcore <file>       load the kernel from a core dump.\n");
#endif /* defined(FEATURE_ELF) */
	printf("  --pevent:vdso-x64 <file>    use <file> as 64-bit vdso.\n");
	printf("  --pevent:vdso-x32 <file>    use <file> as x32 vdso.\n");
	printf("  --pevent:vdso-ia32 <file>   use <file> as 32-bit vdso.\n");
#endif /* defined(FEATURE_PEVENT) */
#endif /* defined(FEATURE_SIDEBAND) */
	printf("  --verbose|-v                         print various information (even when quiet).\n");
	printf("  --pt <file>[:<from>[-<to>]]          load the processor trace data from <file>.\n");
	printf("                                       an optional offset or range can be given.\n");
#if defined(FEATURE_ELF)
	printf("  --elf <<file>[:<base>]               load an ELF from <file> at address <base>.\n");
	printf("                                       use the default load address if <base> is omitted.\n");
#endif /* defined(FEATURE_ELF) */
	printf("  --raw <file>[:<from>[-<to>]]:<base>  load a raw binary from <file> at address <base>.\n");
	printf("                                       an optional offset or range can be given.\n");
	printf("  --cpu none|auto|f/m[/s]              set cpu to the given value and decode according to:\n");
	printf("                                         none     spec (default)\n");
	printf("                                         auto     current cpu\n");
	printf("                                         f/m[/s]  family/model[/stepping]\n");
	printf("  --mtc-freq <n>                       set the MTC frequency (IA32_RTIT_CTL[17:14]) to <n>.\n");
	printf("  --nom-freq <n>                       set the nominal frequency (MSR_PLATFORM_INFO[15:8]) to <n>.\n");
	printf("  --cpuid-0x15.eax                     set the value of cpuid[0x15].eax.\n");
	printf("  --cpuid-0x15.ebx                     set the value of cpuid[0x15].ebx.\n");
	printf("  --insn-decoder                       use the instruction flow decoder (default).\n");
	printf("  --insn:keep-tcal-on-ovf              preserve timing calibration on overflow.\n");
	printf("  --block-decoder                      use the block decoder.\n");
	printf("  --block:show-blocks                  show blocks in the output.\n");
	printf("  --block:end-on-call                  set the end-on-call block decoder flag.\n");
	printf("  --block:end-on-jump                  set the end-on-jump block decoder flag.\n");
	printf("  --block:keep-tcal-on-ovf             preserve timing calibration on overflow.\n");
	printf("\n");
#if defined(FEATURE_ELF)
	printf("You must specify at least one binary or ELF file (--raw|--elf).\n");
#else /* defined(FEATURE_ELF) */
	printf("You must specify at least one binary file (--raw).\n");
#endif /* defined(FEATURE_ELF) */
	printf("You must specify exactly one processor trace file (--pt).\n");
}

static int extract_base(char *arg, uint64_t *base)
{
	char *sep, *rest;

	sep = strrchr(arg, ':');
	if (sep) {
		uint64_t num;

		if (!sep[1])
			return 0;

		errno = 0;
		num = strtoull(sep+1, &rest, 0);
		if (errno || *rest)
			return 0;

		*base = num;
		*sep = 0;
		return 1;
	}

	return 0;
}

static int parse_range(const char *arg, uint64_t *begin, uint64_t *end)
{
	char *rest;

	if (!arg || !*arg)
		return 0;

	errno = 0;
	*begin = strtoull(arg, &rest, 0);
	if (errno)
		return -1;

	if (!*rest)
		return 1;

	if (*rest != '-')
		return -1;

	*end = strtoull(rest+1, &rest, 0);
	if (errno || *rest)
		return -1;

	return 2;
}

/* Preprocess a filename argument.
 *
 * A filename may optionally be followed by a file offset or a file range
 * argument separated by ':'.  Split the original argument into the filename
 * part and the offset/range part.
 *
 * If no end address is specified, set @size to zero.
 * If no offset is specified, set @offset to zero.
 *
 * Returns zero on success, a negative error code otherwise.
 */
static int preprocess_filename(char *filename, uint64_t *offset, uint64_t *size)
{
	uint64_t begin, end;
	char *range;
	int parts;

	if (!filename || !offset || !size)
		return -pte_internal;

	/* Search from the end as the filename may also contain ':'. */
	range = strrchr(filename, ':');
	if (!range) {
		*offset = 0ull;
		*size = 0ull;

		return 0;
	}

	/* Let's try to parse an optional range suffix.
	 *
	 * If we can, remove it from the filename argument.
	 * If we can not, assume that the ':' is part of the filename, e.g. a
	 * drive letter on Windows.
	 */
	parts = parse_range(range + 1, &begin, &end);
	if (parts <= 0) {
		*offset = 0ull;
		*size = 0ull;

		return 0;
	}

	if (parts == 1) {
		*offset = begin;
		*size = 0ull;

		*range = 0;

		return 0;
	}

	if (parts == 2) {
		if (end <= begin)
			return -pte_invalid;

		*offset = begin;
		*size = end - begin;

		*range = 0;

		return 0;
	}

	return -pte_internal;
}

static int load_file(uint8_t **buffer, size_t *psize, const char *filename,
		     uint64_t offset, uint64_t size, const char *prog)
{
	uint8_t *content;
	size_t read;
	FILE *file;
	long fsize, begin, end;
	int errcode;

	if (!buffer || !psize || !filename || !prog) {
		fprintf(stderr, "%s: internal error.\n", prog ? prog : "");
		return -1;
	}

	errno = 0;
	file = fopen(filename, "rb");
	if (!file) {
		fprintf(stderr, "%s: failed to open %s: %d.\n",
			prog, filename, errno);
		return -1;
	}

	errcode = fseek(file, 0, SEEK_END);
	if (errcode) {
		fprintf(stderr, "%s: failed to determine size of %s: %d.\n",
			prog, filename, errno);
		goto err_file;
	}

	fsize = ftell(file);
	if (fsize < 0) {
		fprintf(stderr, "%s: failed to determine size of %s: %d.\n",
			prog, filename, errno);
		goto err_file;
	}

	begin = (long) offset;
	if (((uint64_t) begin != offset) || (fsize <= begin)) {
		fprintf(stderr,
			"%s: bad offset 0x%" PRIx64 " into %s.\n",
			prog, offset, filename);
		goto err_file;
	}

	end = fsize;
	if (size) {
		uint64_t range_end;

		range_end = offset + size;
		if ((uint64_t) end < range_end) {
			fprintf(stderr,
				"%s: bad range 0x%" PRIx64 " in %s.\n",
				prog, range_end, filename);
			goto err_file;
		}

		end = (long) range_end;
	}

	fsize = end - begin;

	content = malloc((size_t) fsize);
	if (!content) {
		fprintf(stderr, "%s: failed to allocated memory %s.\n",
			prog, filename);
		goto err_file;
	}

	errcode = fseek(file, begin, SEEK_SET);
	if (errcode) {
		fprintf(stderr, "%s: failed to load %s: %d.\n",
			prog, filename, errno);
		goto err_content;
	}

	read = fread(content, (size_t) fsize, 1u, file);
	if (read != 1) {
		fprintf(stderr, "%s: failed to load %s: %d.\n",
			prog, filename, errno);
		goto err_content;
	}

	fclose(file);

	*buffer = content;
	*psize = (size_t) fsize;

	return 0;

err_content:
	free(content);

err_file:
	fclose(file);
	return -1;
}

static int load_pt(struct pt_config *config, char *arg, const char *prog)
{
	uint64_t foffset, fsize;
	uint8_t *buffer;
	size_t size;
	int errcode;

	errcode = preprocess_filename(arg, &foffset, &fsize);
	if (errcode < 0) {
		fprintf(stderr, "%s: bad file %s: %s.\n", prog, arg,
			pt_errstr(pt_errcode(errcode)));
		return -1;
	}

	errcode = load_file(&buffer, &size, arg, foffset, fsize, prog);
	if (errcode < 0)
		return errcode;

	config->begin = buffer;
	config->end = buffer + size;

	return 0;
}

static int load_raw(struct pt_image_section_cache *iscache,
		    struct pt_image *image, char *arg, const char *prog)
{
	uint64_t base, foffset, fsize;
	int isid, errcode, has_base;

	has_base = extract_base(arg, &base);
	if (has_base <= 0) {
		fprintf(stderr, "%s: failed to parse base address"
			"from '%s'.\n", prog, arg);
		return -1;
	}

	errcode = preprocess_filename(arg, &foffset, &fsize);
	if (errcode < 0) {
		fprintf(stderr, "%s: bad file %s: %s.\n", prog, arg,
			pt_errstr(pt_errcode(errcode)));
		return -1;
	}

	if (!fsize)
		fsize = UINT64_MAX;

	isid = pt_iscache_add_file(iscache, arg, foffset, fsize, base);
	if (isid < 0) {
		fprintf(stderr, "%s: failed to add %s at 0x%" PRIx64 ": %s.\n",
			prog, arg, base, pt_errstr(pt_errcode(isid)));
		return -1;
	}

	errcode = pt_image_add_cached(image, iscache, isid, NULL);
	if (errcode < 0) {
		fprintf(stderr, "%s: failed to add %s at 0x%" PRIx64 ": %s.\n",
			prog, arg, base, pt_errstr(pt_errcode(errcode)));
		return -1;
	}

	return 0;
}

static xed_machine_mode_enum_t translate_mode(enum pt_exec_mode mode)
{
	switch (mode) {
	case ptem_unknown:
		return XED_MACHINE_MODE_INVALID;

	case ptem_16bit:
		return XED_MACHINE_MODE_LEGACY_16;

	case ptem_32bit:
		return XED_MACHINE_MODE_LEGACY_32;

	case ptem_64bit:
		return XED_MACHINE_MODE_LONG_64;
	}

	return XED_MACHINE_MODE_INVALID;
}

static const char *visualize_iclass(enum pt_insn_class iclass)
{
	switch (iclass) {
	case ptic_error:
		return "unknown/error";

	case ptic_other:
		return "other";

	case ptic_call:
		return "near call";

	case ptic_return:
		return "near return";

	case ptic_jump:
		return "near jump";

	case ptic_cond_jump:
		return "cond jump";

	case ptic_far_call:
		return "far call";

	case ptic_far_return:
		return "far return";

	case ptic_far_jump:
		return "far jump";

	case ptic_ptwrite:
		return "ptwrite";
	}

	return "undefined";
}

static void check_insn_iclass(const xed_inst_t *inst,
			      const struct pt_insn *insn, uint64_t offset)
{
	xed_category_enum_t category;
	xed_iclass_enum_t iclass;

	if (!inst || !insn) {
		printf("[internal error]\n");
		return;
	}

	category = xed_inst_category(inst);
	iclass = xed_inst_iclass(inst);

	switch (insn->iclass) {
	case ptic_error:
		break;

	case ptic_ptwrite:
	case ptic_other:
		switch (category) {
		default:
			return;

		case XED_CATEGORY_CALL:
		case XED_CATEGORY_RET:
		case XED_CATEGORY_UNCOND_BR:
		case XED_CATEGORY_SYSCALL:
		case XED_CATEGORY_SYSRET:
			break;

		case XED_CATEGORY_COND_BR:
			switch (iclass) {
			case XED_ICLASS_XBEGIN:
			case XED_ICLASS_XEND:
				return;

			default:
				break;
			}
			break;

		case XED_CATEGORY_INTERRUPT:
			switch (iclass) {
			case XED_ICLASS_BOUND:
				return;

			default:
				break;
			}
			break;
		}
		break;

	case ptic_call:
		if (iclass == XED_ICLASS_CALL_NEAR)
			return;

		break;

	case ptic_return:
		if (iclass == XED_ICLASS_RET_NEAR)
			return;

		break;

	case ptic_jump:
		if (iclass == XED_ICLASS_JMP)
			return;

		break;

	case ptic_cond_jump:
		if (category == XED_CATEGORY_COND_BR)
			return;

		break;

	case ptic_far_call:
		switch (iclass) {
		default:
			break;

		case XED_ICLASS_CALL_FAR:
		case XED_ICLASS_INT:
		case XED_ICLASS_INT1:
		case XED_ICLASS_INT3:
		case XED_ICLASS_INTO:
		case XED_ICLASS_SYSCALL:
		case XED_ICLASS_SYSCALL_AMD:
		case XED_ICLASS_SYSENTER:
		case XED_ICLASS_VMCALL:
			return;
		}
		break;

	case ptic_far_return:
		switch (iclass) {
		default:
			break;

		case XED_ICLASS_RET_FAR:
		case XED_ICLASS_IRET:
		case XED_ICLASS_IRETD:
		case XED_ICLASS_IRETQ:
		case XED_ICLASS_SYSRET:
		case XED_ICLASS_SYSRET_AMD:
		case XED_ICLASS_SYSEXIT:
		case XED_ICLASS_VMLAUNCH:
		case XED_ICLASS_VMRESUME:
			return;
		}
		break;

	case ptic_far_jump:
		if (iclass == XED_ICLASS_JMP_FAR)
			return;

		break;
	}

	/* If we get here, @insn->iclass doesn't match XED's classification. */
	printf("[%" PRIx64 ", %" PRIx64 ": iclass error: iclass: %s, "
	       "xed iclass: %s, category: %s]\n", offset, insn->ip,
	       visualize_iclass(insn->iclass), xed_iclass_enum_t2str(iclass),
	       xed_category_enum_t2str(category));

}

static void check_insn_decode(xed_decoded_inst_t *inst,
			      const struct pt_insn *insn, uint64_t offset)
{
	xed_error_enum_t errcode;

	if (!inst || !insn) {
		printf("[internal error]\n");
		return;
	}

	xed_decoded_inst_set_mode(inst, translate_mode(insn->mode),
				  XED_ADDRESS_WIDTH_INVALID);

	/* Decode the instruction (again).
	 *
	 * We may have decoded the instruction already for printing.  In this
	 * case, we will decode it twice.
	 *
	 * The more common use-case, however, is to check the instruction class
	 * while not printing instructions since the latter is too expensive for
	 * regular use with long traces.
	 */
	errcode = xed_decode(inst, insn->raw, insn->size);
	if (errcode != XED_ERROR_NONE) {
		printf("[%" PRIx64 ", %" PRIx64 ": xed error: (%u) %s]\n",
		       offset, insn->ip, errcode,
		       xed_error_enum_t2str(errcode));
		return;
	}

	if (!xed_decoded_inst_valid(inst)) {
		printf("[%" PRIx64 ", %" PRIx64 ": xed error: "
		       "invalid instruction]\n", offset, insn->ip);
		return;
	}
}

static void check_insn(const struct pt_insn *insn, uint64_t offset)
{
	xed_decoded_inst_t inst;

	if (!insn) {
		printf("[internal error]\n");
		return;
	}

	if (insn->isid <= 0)
		printf("[%" PRIx64 ", %" PRIx64 ": check error: "
		       "bad isid]\n", offset, insn->ip);

	xed_decoded_inst_zero(&inst);
	check_insn_decode(&inst, insn, offset);

	/* We need a valid instruction in order to do further checks.
	 *
	 * Invalid instructions have already been diagnosed.
	 */
	if (!xed_decoded_inst_valid(&inst))
		return;

	check_insn_iclass(xed_decoded_inst_inst(&inst), insn, offset);
}

static void print_raw_insn(const struct pt_insn *insn)
{
	uint8_t length, idx;

	if (!insn) {
		printf("[internal error]");
		return;
	}

	length = insn->size;
	if (sizeof(insn->raw) < length)
		length = sizeof(insn->raw);

	for (idx = 0; idx < length; ++idx)
		printf(" %02x", insn->raw[idx]);

	for (; idx < pt_max_insn_size; ++idx)
		printf("   ");
}

static void xed_print_insn(const xed_decoded_inst_t *inst, uint64_t ip,
			   const struct ptxed_options *options)
{
	xed_print_info_t pi;
	char buffer[256];
	xed_bool_t ok;

	if (!inst || !options) {
		printf(" [internal error]");
		return;
	}

	if (options->print_raw_insn) {
		xed_uint_t length, i;

		length = xed_decoded_inst_get_length(inst);
		for (i = 0; i < length; ++i)
			printf(" %02x", xed_decoded_inst_get_byte(inst, i));

		for (; i < pt_max_insn_size; ++i)
			printf("   ");
	}

	xed_init_print_info(&pi);
	pi.p = inst;
	pi.buf = buffer;
	pi.blen = sizeof(buffer);
	pi.runtime_address = ip;

	if (options->att_format)
		pi.syntax = XED_SYNTAX_ATT;

	ok = xed_format_generic(&pi);
	if (!ok) {
		printf(" [xed print error]");
		return;
	}

	printf("  %s", buffer);
}

static void print_insn(const struct pt_insn *insn, xed_state_t *xed,
		       const struct ptxed_options *options, uint64_t offset,
		       uint64_t time)
{
	if (!insn || !options) {
		printf("[internal error]\n");
		return;
	}

	if (options->print_offset)
		printf("%016" PRIx64 "  ", offset);

	if (options->print_time)
		printf("%016" PRIx64 "  ", time);

	if (insn->speculative)
		printf("? ");

	printf("%016" PRIx64, insn->ip);

	if (!options->dont_print_insn) {
		xed_machine_mode_enum_t mode;
		xed_decoded_inst_t inst;
		xed_error_enum_t errcode;

		mode = translate_mode(insn->mode);

		xed_state_set_machine_mode(xed, mode);
		xed_decoded_inst_zero_set_mode(&inst, xed);

		errcode = xed_decode(&inst, insn->raw, insn->size);
		switch (errcode) {
		case XED_ERROR_NONE:
			xed_print_insn(&inst, insn->ip, options);
			break;

		default:
			print_raw_insn(insn);

			printf(" [xed decode error: (%u) %s]", errcode,
			       xed_error_enum_t2str(errcode));
			break;
		}
	}

	printf("\n");
}

static const char *print_exec_mode(enum pt_exec_mode mode)
{
	switch (mode) {
	case ptem_unknown:
		return "<unknown>";

	case ptem_16bit:
		return "16-bit";

	case ptem_32bit:
		return "32-bit";

	case ptem_64bit:
		return "64-bit";
	}

	return "<invalid>";
}

static void print_event(const struct pt_event *event,
			const struct ptxed_options *options, uint64_t offset)
{
	if (!event || !options) {
		printf("[internal error]\n");
		return;
	}

	printf("[");

	if (options->print_offset)
		printf("%016" PRIx64 "  ", offset);

	if (options->print_event_time && event->has_tsc)
		printf("%016" PRIx64 "  ", event->tsc);

	switch (event->type) {
	case ptev_enabled:
		printf("%s", event->variant.enabled.resumed ? "resumed" :
		       "enabled");

		if (options->print_event_ip)
			printf(", ip: %016" PRIx64, event->variant.enabled.ip);
		break;

	case ptev_disabled:
		printf("disabled");

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.disabled.ip);
		break;

	case ptev_async_disabled:
		printf("disabled");

		if (options->print_event_ip) {
			printf(", at: %016" PRIx64,
			       event->variant.async_disabled.at);

			if (!event->ip_suppressed)
				printf(", ip: %016" PRIx64,
				       event->variant.async_disabled.ip);
		}
		break;

	case ptev_async_branch:
		printf("interrupt");

		if (options->print_event_ip) {
			printf(", from: %016" PRIx64,
			       event->variant.async_branch.from);

			if (!event->ip_suppressed)
				printf(", to: %016" PRIx64,
				       event->variant.async_branch.to);
		}
		break;

	case ptev_paging:
		printf("paging, cr3: %016" PRIx64 "%s",
		       event->variant.paging.cr3,
		       event->variant.paging.non_root ? ", nr" : "");
		break;

	case ptev_async_paging:
		printf("paging, cr3: %016" PRIx64 "%s",
		       event->variant.async_paging.cr3,
		       event->variant.async_paging.non_root ? ", nr" : "");

		if (options->print_event_ip)
			printf(", ip: %016" PRIx64,
			       event->variant.async_paging.ip);
		break;

	case ptev_overflow:
		printf("overflow");

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.overflow.ip);
		break;

	case ptev_exec_mode:
		printf("exec mode: %s",
		       print_exec_mode(event->variant.exec_mode.mode));

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64,
			       event->variant.exec_mode.ip);
		break;

	case ptev_tsx:
		if (event->variant.tsx.aborted)
			printf("aborted");
		else if (event->variant.tsx.speculative)
			printf("begin transaction");
		else
			printf("committed");

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.tsx.ip);
		break;

	case ptev_stop:
		printf("stopped");
		break;

	case ptev_vmcs:
		printf("vmcs, base: %016" PRIx64, event->variant.vmcs.base);
		break;

	case ptev_async_vmcs:
		printf("vmcs, base: %016" PRIx64,
		       event->variant.async_vmcs.base);

		if (options->print_event_ip)
			printf(", ip: %016" PRIx64,
			       event->variant.async_vmcs.ip);
		break;

	case ptev_exstop:
		printf("exstop");

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.exstop.ip);
		break;

	case ptev_mwait:
		printf("mwait %" PRIx32 " %" PRIx32,
		       event->variant.mwait.hints, event->variant.mwait.ext);

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.mwait.ip);
		break;

	case ptev_pwre:
		printf("pwre c%u.%u", (event->variant.pwre.state + 1) & 0xf,
		       (event->variant.pwre.sub_state + 1) & 0xf);

		if (event->variant.pwre.hw)
			printf(" hw");
		break;


	case ptev_pwrx:
		printf("pwrx ");

		if (event->variant.pwrx.interrupt)
			printf("int: ");

		if (event->variant.pwrx.store)
			printf("st: ");

		if (event->variant.pwrx.autonomous)
			printf("hw: ");

		printf("c%u (c%u)", (event->variant.pwrx.last + 1) & 0xf,
		       (event->variant.pwrx.deepest + 1) & 0xf);
		break;

	case ptev_ptwrite:
		printf("ptwrite: %" PRIx64, event->variant.ptwrite.payload);

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.ptwrite.ip);
		break;

	case ptev_tick:
		printf("tick");

		if (options->print_event_ip && !event->ip_suppressed)
			printf(", ip: %016" PRIx64, event->variant.tick.ip);
		break;

	case ptev_cbr:
		printf("cbr: %x", event->variant.cbr.ratio);
		break;

	case ptev_mnt:
		printf("mnt: %" PRIx64, event->variant.mnt.payload);
		break;
	}

	printf("]\n");
}

static void diagnose(struct ptxed_decoder *decoder, uint64_t ip,
		     const char *errtype, int errcode)
{
	int err;
	uint64_t pos;

	err = -pte_internal;
	pos = 0ull;

	switch (decoder->type) {
	case pdt_insn_decoder:
		err = pt_insn_get_offset(decoder->variant.insn, &pos);
		break;

	case pdt_block_decoder:
		err = pt_blk_get_offset(decoder->variant.block, &pos);
		break;
	}

	if (err < 0) {
		printf("could not determine offset: %s\n",
		       pt_errstr(pt_errcode(err)));
		printf("[?, %" PRIx64 ": %s: %s]\n", ip, errtype,
		       pt_errstr(pt_errcode(errcode)));
	} else
		printf("[%" PRIx64 ", %" PRIx64 ": %s: %s]\n", pos,
		       ip, errtype, pt_errstr(pt_errcode(errcode)));
}

#if defined(FEATURE_SIDEBAND)

static int ptxed_sb_event(struct ptxed_decoder *decoder,
			  const struct pt_event *event,
			  const struct ptxed_options *options)
{
	struct pt_image *image;
	int errcode;

	if (!decoder || !event || !options)
		return -pte_internal;

	image = NULL;
	errcode = pt_sb_event(decoder->session, &image, event, sizeof(*event),
			      stdout, options->sb_dump_flags);
	if (errcode < 0)
		return errcode;

	if (!image)
		return 0;

	switch (decoder->type) {
	case pdt_insn_decoder:
		return pt_insn_set_image(decoder->variant.insn, image);

	case pdt_block_decoder:
		return pt_blk_set_image(decoder->variant.block, image);
	}

	return -pte_internal;
}

#endif /* defined(FEATURE_SIDEBAND) */

static int drain_events_insn(struct ptxed_decoder *decoder, uint64_t *time,
			     int status, const struct ptxed_options *options)
{
	struct pt_insn_decoder *ptdec;
	int errcode;

	if (!decoder || !time || !options)
		return -pte_internal;

	ptdec = decoder->variant.insn;

	while (status & pts_event_pending) {
		struct pt_event event;
		uint64_t offset;

		offset = 0ull;
		if (options->print_offset) {
			errcode = pt_insn_get_offset(ptdec, &offset);
			if (errcode < 0)
				return errcode;
		}

		status = pt_insn_event(ptdec, &event, sizeof(event));
		if (status < 0)
			return status;

		*time = event.tsc;

		if (!options->quiet && !event.status_update)
			print_event(&event, options, offset);

#if defined(FEATURE_SIDEBAND)
		errcode = ptxed_sb_event(decoder, &event, options);
		if (errcode < 0)
			return errcode;
#endif /* defined(FEATURE_SIDEBAND) */
	}

	return status;
}

static void decode_insn(struct ptxed_decoder *decoder,
			const struct ptxed_options *options,
			struct ptxed_stats *stats)
{
	struct pt_insn_decoder *ptdec;
	xed_state_t xed;
	uint64_t offset, sync, time;

	if (!decoder || !options) {
		printf("[internal error]\n");
		return;
	}

	xed_state_zero(&xed);

	ptdec = decoder->variant.insn;
	offset = 0ull;
	sync = 0ull;
	time = 0ull;
	for (;;) {
		struct pt_insn insn;
		int status;

		/* Initialize the IP - we use it for error reporting. */
		insn.ip = 0ull;

		status = pt_insn_sync_forward(ptdec);
		if (status < 0) {
			uint64_t new_sync;
			int errcode;

			if (status == -pte_eos)
				break;

			diagnose(decoder, insn.ip, "sync error", status);

			/* Let's see if we made any progress.  If we haven't,
			 * we likely never will.  Bail out.
			 *
			 * We intentionally report the error twice to indicate
			 * that we tried to re-sync.  Maybe it even changed.
			 */
			errcode = pt_insn_get_offset(ptdec, &new_sync);
			if (errcode < 0 || (new_sync <= sync))
				break;

			sync = new_sync;
			continue;
		}

		for (;;) {
			status = drain_events_insn(decoder, &time, status,
						   options);
			if (status < 0)
				break;

			if (status & pts_eos) {
				if (!(status & pts_ip_suppressed) &&
				    !options->quiet)
					printf("[end of trace]\n");

				status = -pte_eos;
				break;
			}

			if (options->print_offset || options->check) {
				int errcode;

				errcode = pt_insn_get_offset(ptdec, &offset);
				if (errcode < 0)
					break;
			}

			status = pt_insn_next(ptdec, &insn, sizeof(insn));
			if (status < 0) {
				/* Even in case of errors, we may have succeeded
				 * in decoding the current instruction.
				 */
				if (insn.iclass != ptic_error) {
					if (!options->quiet)
						print_insn(&insn, &xed, options,
							   offset, time);
					if (stats)
						stats->insn += 1;

					if (options->check)
						check_insn(&insn, offset);
				}
				break;
			}

			if (!options->quiet)
				print_insn(&insn, &xed, options, offset, time);

			if (stats)
				stats->insn += 1;

			if (options->check)
				check_insn(&insn, offset);
		}

		/* We shouldn't break out of the loop without an error. */
		if (!status)
			status = -pte_internal;

		/* We're done when we reach the end of the trace stream. */
		if (status == -pte_eos)
			break;

		diagnose(decoder, insn.ip, "error",  status);
	}
}

static int xed_next_ip(uint64_t *pip, const xed_decoded_inst_t *inst,
		       uint64_t ip)
{
	xed_uint_t length, disp_width;

	if (!pip || !inst)
		return -pte_internal;

	length = xed_decoded_inst_get_length(inst);
	if (!length) {
		printf("[xed error: failed to determine instruction length]\n");
		return -pte_bad_insn;
	}

	ip += length;

	/* If it got a branch displacement it must be a branch.
	 *
	 * This includes conditional branches for which we don't know whether
	 * they were taken.  The next IP won't be used in this case as a
	 * conditional branch ends a block.  The next block will start with the
	 * correct IP.
	 */
	disp_width = xed_decoded_inst_get_branch_displacement_width(inst);
	if (disp_width)
		ip += (uint64_t) (int64_t)
			xed_decoded_inst_get_branch_displacement(inst);

	*pip = ip;
	return 0;
}

static int block_fetch_insn(struct pt_insn *insn, const struct pt_block *block,
			    uint64_t ip, struct pt_image_section_cache *iscache)
{
	if (!insn || !block)
		return -pte_internal;

	/* We can't read from an empty block. */
	if (!block->ninsn)
		return -pte_invalid;

	memset(insn, 0, sizeof(*insn));
	insn->mode = block->mode;
	insn->isid = block->isid;
	insn->ip = ip;

	/* The last instruction in a block may be truncated. */
	if ((ip == block->end_ip) && block->truncated) {
		if (!block->size || (sizeof(insn->raw) < (size_t) block->size))
			return -pte_bad_insn;

		insn->size = block->size;
		memcpy(insn->raw, block->raw, insn->size);
	} else {
		int size;

		size = pt_iscache_read(iscache, insn->raw, sizeof(insn->raw),
				       insn->isid, ip);
		if (size < 0)
			return size;

		insn->size = (uint8_t) size;
	}

	return 0;
}

static void diagnose_block(struct ptxed_decoder *decoder,
			   const char *errtype, int errcode,
			   const struct pt_block *block)
{
	uint64_t ip;
	int err;

	if (!decoder || !block) {
		printf("ptxed: internal error");
		return;
	}

	/* Determine the IP at which to report the error.
	 *
	 * Depending on the type of error, the IP varies between that of the
	 * last instruction in @block or the next instruction outside of @block.
	 *
	 * When the block is empty, we use the IP of the block itself,
	 * i.e. where the first instruction should have been.
	 */
	if (!block->ninsn)
		ip = block->ip;
	else {
		ip = block->end_ip;

		switch (errcode) {
		case -pte_nomap:
		case -pte_bad_insn: {
			struct pt_insn insn;
			xed_decoded_inst_t inst;
			xed_error_enum_t xederr;

			/* Decode failed when trying to fetch or decode the next
			 * instruction.  Since indirect or conditional branches
			 * end a block and don't cause an additional fetch, we
			 * should be able to reach that IP from the last
			 * instruction in @block.
			 *
			 * We ignore errors and fall back to the IP of the last
			 * instruction.
			 */
			err = block_fetch_insn(&insn, block, ip,
					       decoder->iscache);
			if (err < 0)
				break;

			xed_decoded_inst_zero(&inst);
			xed_decoded_inst_set_mode(&inst,
						  translate_mode(insn.mode),
						  XED_ADDRESS_WIDTH_INVALID);

			xederr = xed_decode(&inst, insn.raw, insn.size);
			if (xederr != XED_ERROR_NONE)
				break;

			(void) xed_next_ip(&ip, &inst, insn.ip);
		}
			break;

		default:
			break;
		}
	}

	diagnose(decoder, ip, errtype, errcode);
}

static void print_block(struct ptxed_decoder *decoder,
			const struct pt_block *block,
			const struct ptxed_options *options,
			const struct ptxed_stats *stats,
			uint64_t offset, uint64_t time)
{
	xed_machine_mode_enum_t mode;
	xed_state_t xed;
	uint64_t ip;
	uint16_t ninsn;

	if (!block || !options) {
		printf("[internal error]\n");
		return;
	}

	if (options->track_blocks) {
		printf("[block");
		if (stats)
			printf(" %" PRIx64, stats->blocks);
		printf("]\n");
	}

	mode = translate_mode(block->mode);
	xed_state_init2(&xed, mode, XED_ADDRESS_WIDTH_INVALID);

	/* There's nothing to do for empty blocks. */
	ninsn = block->ninsn;
	if (!ninsn)
		return;

	ip = block->ip;
	for (;;) {
		struct pt_insn insn;
		xed_decoded_inst_t inst;
		xed_error_enum_t xederrcode;
		int errcode;

		if (options->print_offset)
			printf("%016" PRIx64 "  ", offset);

		if (options->print_time)
			printf("%016" PRIx64 "  ", time);

		if (block->speculative)
			printf("? ");

		printf("%016" PRIx64, ip);

		errcode = block_fetch_insn(&insn, block, ip, decoder->iscache);
		if (errcode < 0) {
			printf(" [fetch error: %s]\n",
			       pt_errstr(pt_errcode(errcode)));
			break;
		}

		xed_decoded_inst_zero_set_mode(&inst, &xed);

		xederrcode = xed_decode(&inst, insn.raw, insn.size);
		if (xederrcode != XED_ERROR_NONE) {
			print_raw_insn(&insn);

			printf(" [xed decode error: (%u) %s]\n", xederrcode,
			       xed_error_enum_t2str(xederrcode));
			break;
		}

		if (!options->dont_print_insn)
			xed_print_insn(&inst, insn.ip, options);

		printf("\n");

		ninsn -= 1;
		if (!ninsn)
			break;

		errcode = xed_next_ip(&ip, &inst, ip);
		if (errcode < 0) {
			diagnose(decoder, ip, "reconstruct error", errcode);
			break;
		}
	}

	/* Decode should have brought us to @block->end_ip. */
	if (ip != block->end_ip)
		diagnose(decoder, ip, "reconstruct error", -pte_nosync);
}

static void check_block(const struct pt_block *block,
			struct pt_image_section_cache *iscache,
			uint64_t offset)
{
	struct pt_insn insn;
	xed_decoded_inst_t inst;
	uint64_t ip;
	uint16_t ninsn;
	int errcode;

	if (!block) {
		printf("[internal error]\n");
		return;
	}

	/* There's nothing to check for an empty block. */
	ninsn = block->ninsn;
	if (!ninsn)
		return;

	if (block->isid <= 0)
		printf("[%" PRIx64 ", %" PRIx64 ": check error: "
		       "bad isid]\n", offset, block->ip);

	ip = block->ip;
	do {
		errcode = block_fetch_insn(&insn, block, ip, iscache);
		if (errcode < 0) {
			printf("[%" PRIx64 ", %" PRIx64 ": fetch error: %s]\n",
			       offset, ip, pt_errstr(pt_errcode(errcode)));
			return;
		}

		xed_decoded_inst_zero(&inst);
		check_insn_decode(&inst, &insn, offset);

		/* We need a valid instruction in order to do further checks.
		 *
		 * Invalid instructions have already been diagnosed.
		 */
		if (!xed_decoded_inst_valid(&inst))
			return;

		errcode = xed_next_ip(&ip, &inst, ip);
		if (errcode < 0) {
			printf("[%" PRIx64 ", %" PRIx64 ": error: %s]\n",
			       offset, ip, pt_errstr(pt_errcode(errcode)));
			return;
		}
	} while (--ninsn);

	/* We reached the end of the block.  Both @insn and @inst refer to the
	 * last instruction in @block.
	 *
	 * Check that we reached the end IP of the block.
	 */
	if (insn.ip != block->end_ip) {
		printf("[%" PRIx64 ", %" PRIx64 ": error: did not reach end: %"
		       PRIx64 "]\n", offset, insn.ip, block->end_ip);
	}

	/* Check the last instruction's classification, if available. */
	insn.iclass = block->iclass;
	if (insn.iclass)
		check_insn_iclass(xed_decoded_inst_inst(&inst), &insn, offset);
}

static int drain_events_block(struct ptxed_decoder *decoder, uint64_t *time,
			      int status, const struct ptxed_options *options)
{
	struct pt_block_decoder *ptdec;
	int errcode;

	if (!decoder || !time || !options)
		return -pte_internal;

	ptdec = decoder->variant.block;

	while (status & pts_event_pending) {
		struct pt_event event;
		uint64_t offset;

		offset = 0ull;
		if (options->print_offset) {
			errcode = pt_blk_get_offset(ptdec, &offset);
			if (errcode < 0)
				return errcode;
		}

		status = pt_blk_event(ptdec, &event, sizeof(event));
		if (status < 0)
			return status;

		*time = event.tsc;

		if (!options->quiet && !event.status_update)
			print_event(&event, options, offset);

#if defined(FEATURE_SIDEBAND)
		errcode = ptxed_sb_event(decoder, &event, options);
		if (errcode < 0)
			return errcode;
#endif /* defined(FEATURE_SIDEBAND) */
	}

	return status;
}

static void decode_block(struct ptxed_decoder *decoder,
			 const struct ptxed_options *options,
			 struct ptxed_stats *stats)
{
	struct pt_image_section_cache *iscache;
	struct pt_block_decoder *ptdec;
	uint64_t offset, sync, time;

	if (!decoder || !options) {
		printf("[internal error]\n");
		return;
	}

	iscache = decoder->iscache;
	ptdec = decoder->variant.block;
	offset = 0ull;
	sync = 0ull;
	time = 0ull;
	for (;;) {
		struct pt_block block;
		int status;

		/* Initialize IP and ninsn - we use it for error reporting. */
		block.ip = 0ull;
		block.ninsn = 0u;

		status = pt_blk_sync_forward(ptdec);
		if (status < 0) {
			uint64_t new_sync;
			int errcode;

			if (status == -pte_eos)
				break;

			diagnose_block(decoder, "sync error", status, &block);

			/* Let's see if we made any progress.  If we haven't,
			 * we likely never will.  Bail out.
			 *
			 * We intentionally report the error twice to indicate
			 * that we tried to re-sync.  Maybe it even changed.
			 */
			errcode = pt_blk_get_offset(ptdec, &new_sync);
			if (errcode < 0 || (new_sync <= sync))
				break;

			sync = new_sync;
			continue;
		}

		for (;;) {
			status = drain_events_block(decoder, &time, status,
						    options);
			if (status < 0)
				break;

			if (status & pts_eos) {
				if (!(status & pts_ip_suppressed) &&
				    !options->quiet)
					printf("[end of trace]\n");

				status = -pte_eos;
				break;
			}

			if (options->print_offset || options->check) {
				int errcode;

				errcode = pt_blk_get_offset(ptdec, &offset);
				if (errcode < 0)
					break;
			}

			status = pt_blk_next(ptdec, &block, sizeof(block));
			if (status < 0) {
				/* Even in case of errors, we may have succeeded
				 * in decoding some instructions.
				 */
				if (block.ninsn) {
					if (stats) {
						stats->insn += block.ninsn;
						stats->blocks += 1;
					}

					if (!options->quiet)
						print_block(decoder, &block,
							    options, stats,
							    offset, time);

					if (options->check)
						check_block(&block, iscache,
							    offset);
				}
				break;
			}

			if (stats) {
				stats->insn += block.ninsn;
				stats->blocks += 1;
			}

			if (!options->quiet)
				print_block(decoder, &block, options, stats,
					    offset, time);

			if (options->check)
				check_block(&block, iscache, offset);
		}

		/* We shouldn't break out of the loop without an error. */
		if (!status)
			status = -pte_internal;

		/* We're done when we reach the end of the trace stream. */
		if (status == -pte_eos)
			break;

		diagnose_block(decoder, "error", status, &block);
	}
}

static void decode(struct ptxed_decoder *decoder,
		   const struct ptxed_options *options,
		   struct ptxed_stats *stats)
{
	if (!decoder) {
		printf("[internal error]\n");
		return;
	}

	switch (decoder->type) {
	case pdt_insn_decoder:
		decode_insn(decoder, options, stats);
		break;

	case pdt_block_decoder:
		decode_block(decoder, options, stats);
		break;
	}
}

static int alloc_decoder(struct ptxed_decoder *decoder,
			 const struct pt_config *conf, struct pt_image *image,
			 const struct ptxed_options *options, const char *prog)
{
	struct pt_config config;
	int errcode;

	if (!decoder || !conf || !options || !prog)
		return -pte_internal;

	config = *conf;

	switch (decoder->type) {
	case pdt_insn_decoder:
		config.flags = decoder->insn.flags;

		decoder->variant.insn = pt_insn_alloc_decoder(&config);
		if (!decoder->variant.insn) {
			fprintf(stderr,
				"%s: failed to create decoder.\n", prog);
			return -pte_nomem;
		}

		errcode = pt_insn_set_image(decoder->variant.insn, image);
		if (errcode < 0) {
			fprintf(stderr, "%s: failed to set image.\n", prog);
			return errcode;
		}

		break;

	case pdt_block_decoder:
		config.flags = decoder->block.flags;

		decoder->variant.block = pt_blk_alloc_decoder(&config);
		if (!decoder->variant.block) {
			fprintf(stderr,
				"%s: failed to create  decoder.\n", prog);
			return -pte_nomem;
		}

		errcode = pt_blk_set_image(decoder->variant.block, image);
		if (errcode < 0) {
			fprintf(stderr, "%s: failed to set image.\n", prog);
			return errcode;
		}

		break;
	}

	return 0;
}

static void print_stats(struct ptxed_stats *stats)
{
	if (!stats) {
		printf("[internal error]\n");
		return;
	}

	if (stats->flags & ptxed_stat_insn)
		printf("insn: %" PRIu64 ".\n", stats->insn);

	if (stats->flags & ptxed_stat_blocks)
		printf("blocks:\t%" PRIu64 ".\n", stats->blocks);
}

#if defined(FEATURE_SIDEBAND)

static int ptxed_print_error(int errcode, const char *filename,
			     uint64_t offset, void *priv)
{
	const struct ptxed_options *options;
	const char *errstr, *severity;

	options = (struct ptxed_options *) priv;
	if (!options)
		return -pte_internal;

	if (errcode >= 0 && !options->print_sb_warnings)
		return 0;

	if (!filename)
		filename = "<unknown>";

	severity = errcode < 0 ? "error" : "warning";

	errstr = errcode < 0
		? pt_errstr(pt_errcode(errcode))
		: pt_sb_errstr((enum pt_sb_error_code) errcode);

	if (!errstr)
		errstr = "<unknown error>";

	printf("[%s:%016" PRIx64 " sideband %s: %s]\n", filename, offset,
	       severity, errstr);

	return 0;
}

static int ptxed_print_switch(const struct pt_sb_context *context, void *priv)
{
	struct pt_image *image;
	const char *name;

	if (!priv)
		return -pte_internal;

	image = pt_sb_ctx_image(context);
	if (!image)
		return -pte_internal;

	name = pt_image_name(image);
	if (!name)
		name = "<unknown>";

	printf("[context: %s]\n", name);

	return 0;
}

#if defined(FEATURE_PEVENT)

static int ptxed_sb_pevent(struct ptxed_decoder *decoder, char *filename,
			   const char *prog)
{
	struct pt_sb_pevent_config config;
	uint64_t foffset, fsize, fend;
	int errcode;

	if (!decoder || !prog) {
		fprintf(stderr, "%s: internal error.\n", prog ? prog : "?");
		return -1;
	}

	errcode = preprocess_filename(filename, &foffset, &fsize);
	if (errcode < 0) {
		fprintf(stderr, "%s: bad file %s: %s.\n", prog, filename,
			pt_errstr(pt_errcode(errcode)));
		return -1;
	}

	if (SIZE_MAX < foffset) {
		fprintf(stderr,
			"%s: bad offset: 0x%" PRIx64 ".\n", prog, foffset);
		return -1;
	}

	config = decoder->pevent;
	config.filename = filename;
	config.begin = (size_t) foffset;
	config.end = 0;

	if (fsize) {
		fend = foffset + fsize;
		if ((fend <= foffset) || (SIZE_MAX < fend)) {
			fprintf(stderr,
				"%s: bad range: 0x%" PRIx64 "-0x%" PRIx64 ".\n",
				prog, foffset, fend);
			return -1;
		}

		config.end = (size_t) fend;
	}

	errcode = pt_sb_alloc_pevent_decoder(decoder->session, &config);
	if (errcode < 0) {
		fprintf(stderr, "%s: error loading %s: %s.\n", prog, filename,
			pt_errstr(pt_errcode(errcode)));
		return -1;
	}

	return 0;
}

#endif /* defined(FEATURE_PEVENT) */
#endif /* defined(FEATURE_SIDEBAND) */

static int get_arg_uint64(uint64_t *value, const char *option, const char *arg,
			  const char *prog)
{
	char *rest;

	if (!value || !option || !prog) {
		fprintf(stderr, "%s: internal error.\n", prog ? prog : "?");
		return 0;
	}

	if (!arg || arg[0] == 0 || (arg[0] == '-' && arg[1] == '-')) {
		fprintf(stderr, "%s: %s: missing argument.\n", prog, option);
		return 0;
	}

	errno = 0;
	*value = strtoull(arg, &rest, 0);
	if (errno || *rest) {
		fprintf(stderr, "%s: %s: bad argument: %s.\n", prog, option,
			arg);
		return 0;
	}

	return 1;
}

static int get_arg_uint32(uint32_t *value, const char *option, const char *arg,
			  const char *prog)
{
	uint64_t val;

	if (!get_arg_uint64(&val, option, arg, prog))
		return 0;

	if (val > UINT32_MAX) {
		fprintf(stderr, "%s: %s: value too big: %s.\n", prog, option,
			arg);
		return 0;
	}

	*value = (uint32_t) val;

	return 1;
}

#if defined(FEATURE_SIDEBAND) && defined(FEATURE_PEVENT)

static int get_arg_uint16(uint16_t *value, const char *option, const char *arg,
			  const char *prog)
{
	uint64_t val;

	if (!get_arg_uint64(&val, option, arg, prog))
		return 0;

	if (val > UINT16_MAX) {
		fprintf(stderr, "%s: %s: value too big: %s.\n", prog, option,
			arg);
		return 0;
	}

	*value = (uint16_t) val;

	return 1;
}

#endif /* defined(FEATURE_SIDEBAND) && defined(FEATURE_PEVENT) */

static int get_arg_uint8(uint8_t *value, const char *option, const char *arg,
			 const char *prog)
{
	uint64_t val;

	if (!get_arg_uint64(&val, option, arg, prog))
		return 0;

	if (val > UINT8_MAX) {
		fprintf(stderr, "%s: %s: value too big: %s.\n", prog, option,
			arg);
		return 0;
	}

	*value = (uint8_t) val;

	return 1;
}

static int ptxed_addr_cfg(struct pt_config *config, uint8_t filter,
			  const char *option, const char *arg, const char *prog)
{
	uint64_t addr_cfg;

	if (!config || !option || !arg || !prog) {
		fprintf(stderr, "%s: internal error.\n", prog ? prog : "?");
		return 0;
	}

	if (!get_arg_uint64(&addr_cfg, option, arg, prog))
		return 0;

	if (15 < addr_cfg) {
		fprintf(stderr, "%s: %s: value too big: %s.\n", prog, option,
			arg);
		return 0;
	}

	/* Make sure the shift doesn't overflow. */
	if (15 < filter) {
		fprintf(stderr, "%s: internal error.\n", prog);
		return 0;
	}

	addr_cfg <<= (filter * 4);

	config->addr_filter.config.addr_cfg |= addr_cfg;

	return 1;
}

extern int main(int argc, char *argv[])
{
	struct ptxed_decoder decoder;
	struct ptxed_options options;
	struct ptxed_stats stats;
	struct pt_config config;
	struct pt_image *image;
	const char *prog;
	int errcode, i;

	if (!argc) {
		help("");
		return 1;
	}

	prog = argv[0];
	image = NULL;

	memset(&options, 0, sizeof(options));
	memset(&stats, 0, sizeof(stats));

	pt_config_init(&config);

	errcode = ptxed_init_decoder(&decoder);
	if (errcode < 0) {
		fprintf(stderr,
			"%s: error initializing decoder: %s.\n", prog,
			pt_errstr(pt_errcode(errcode)));
		goto err;
	}

#if defined(FEATURE_SIDEBAND)
	pt_sb_notify_error(decoder.session, ptxed_print_error, &options);
#endif

	image = pt_image_alloc(NULL);
	if (!image) {
		fprintf(stderr, "%s: failed to allocate image.\n", prog);
		goto err;
	}

	for (i = 1; i < argc;) {
		char *arg;

		arg = argv[i++];

		if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
			help(prog);
			goto out;
		}
		if (strcmp(arg, "--version") == 0) {
			pt_print_tool_version(prog);
			goto out;
		}
		if (strcmp(arg, "--pt") == 0) {
			if (argc <= i) {
				fprintf(stderr,
					"%s: --pt: missing argument.\n", prog);
				goto out;
			}
			arg = argv[i++];

			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: duplicate pt sources: %s.\n",
					prog, arg);
				goto err;
			}

			if (config.cpu.vendor) {
				errcode = pt_cpu_errata(&config.errata,
							&config.cpu);
				if (errcode < 0)
					printf("[0, 0: config error: %s]\n",
					       pt_errstr(pt_errcode(errcode)));
			}

			errcode = load_pt(&config, arg, prog);
			if (errcode < 0)
				goto err;

			errcode = alloc_decoder(&decoder, &config, image,
						&options, prog);
			if (errcode < 0)
				goto err;

			continue;
		}
		if (strcmp(arg, "--raw") == 0) {
			if (argc <= i) {
				fprintf(stderr,
					"%s: --raw: missing argument.\n", prog);
				goto out;
			}
			arg = argv[i++];

			errcode = load_raw(decoder.iscache, image, arg, prog);
			if (errcode < 0) {
				fprintf(stderr, "%s: --raw: failed to load "
					"'%s'.\n", prog, arg);
				goto err;
			}

			continue;
		}
#if defined(FEATURE_ELF)
		if (strcmp(arg, "--elf") == 0) {
			uint64_t base;

			if (argc <= i) {
				fprintf(stderr,
					"%s: --elf: missing argument.\n", prog);
				goto out;
			}
			arg = argv[i++];
			base = 0ull;
			errcode = extract_base(arg, &base);
			if (errcode < 0)
				goto err;

			errcode = load_elf(decoder.iscache, image, arg, base,
					   prog, options.track_image);
			if (errcode < 0)
				goto err;

			continue;
		}
#endif /* defined(FEATURE_ELF) */
		if (strcmp(arg, "--att") == 0) {
			options.att_format = 1;
			continue;
		}
		if (strcmp(arg, "--no-inst") == 0) {
			options.dont_print_insn = 1;
			continue;
		}
		if (strcmp(arg, "--quiet") == 0 || strcmp(arg, "-q") == 0) {
			options.quiet = 1;
			continue;
		}
		if (strcmp(arg, "--offset") == 0) {
			options.print_offset = 1;
			continue;
		}
		if (strcmp(arg, "--time") == 0) {
			options.print_time = 1;
			continue;
		}
		if (strcmp(arg, "--raw-insn") == 0) {
			options.print_raw_insn = 1;

			continue;
		}
		if (strcmp(arg, "--event:time") == 0) {
			options.print_event_time = 1;

			continue;
		}
		if (strcmp(arg, "--event:ip") == 0) {
			options.print_event_ip = 1;

			continue;
		}
		if (strcmp(arg, "--event:tick") == 0) {
			decoder.block.flags.variant.block.
				enable_tick_events = 1;
			decoder.insn.flags.variant.insn.enable_tick_events = 1;

			continue;
		}
		if (strcmp(arg, "--filter:addr0_cfg") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!ptxed_addr_cfg(&config, 0, arg, argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr0_a") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr0_a, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr0_b") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr0_b, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr1_cfg") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!ptxed_addr_cfg(&config, 1, arg, argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr1_a") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr1_a, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr1_b") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr1_b, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr2_cfg") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!ptxed_addr_cfg(&config, 2, arg, argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr2_a") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr2_a, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr2_b") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr2_b, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr3_cfg") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!ptxed_addr_cfg(&config, 3, arg, argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr3_a") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr3_a, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--filter:addr3_b") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before --pt.\n",
					prog, arg);
				goto err;
			}

			if (!get_arg_uint64(&config.addr_filter.addr3_b, arg,
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--check") == 0) {
			options.check = 1;
			continue;
		}
		if (strcmp(arg, "--iscache-limit") == 0) {
			uint64_t limit;

			if (!get_arg_uint64(&limit, arg, argv[i++], prog))
				goto err;

			errcode = pt_iscache_set_limit(decoder.iscache, limit);
			if (errcode < 0) {
				fprintf(stderr, "%s: error setting iscache "
					"limit: %s.\n", prog,
					pt_errstr(pt_errcode(errcode)));
				goto err;
			}

			continue;
		}
		if (strcmp(arg, "--stat") == 0) {
			options.print_stats = 1;
			continue;
		}
		if (strcmp(arg, "--stat:insn") == 0) {
			options.print_stats = 1;
			stats.flags |= ptxed_stat_insn;
			continue;
		}
		if (strcmp(arg, "--stat:blocks") == 0) {
			options.print_stats = 1;
			stats.flags |= ptxed_stat_blocks;
			continue;
		}
#if defined(FEATURE_SIDEBAND)
		if ((strcmp(arg, "--sb:compact") == 0) ||
		    (strcmp(arg, "--sb") == 0)) {
			options.sb_dump_flags &= ~(uint32_t) ptsbp_verbose;
			options.sb_dump_flags |= (uint32_t) ptsbp_compact;
			continue;
		}
		if (strcmp(arg, "--sb:verbose") == 0) {
			options.sb_dump_flags &= ~(uint32_t) ptsbp_compact;
			options.sb_dump_flags |= (uint32_t) ptsbp_verbose;
			continue;
		}
		if (strcmp(arg, "--sb:filename") == 0) {
			options.sb_dump_flags |= (uint32_t) ptsbp_filename;
			continue;
		}
		if (strcmp(arg, "--sb:offset") == 0) {
			options.sb_dump_flags |= (uint32_t) ptsbp_file_offset;
			continue;
		}
		if (strcmp(arg, "--sb:time") == 0) {
			options.sb_dump_flags |= (uint32_t) ptsbp_tsc;
			continue;
		}
		if (strcmp(arg, "--sb:switch") == 0) {
			pt_sb_notify_switch(decoder.session, ptxed_print_switch,
					    &options);
			continue;
		}
		if (strcmp(arg, "--sb:warn") == 0) {
			options.print_sb_warnings = 1;
			continue;
		}
#if defined(FEATURE_PEVENT)
		if (strcmp(arg, "--pevent:primary") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:primary: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.primary = 1;
			errcode = ptxed_sb_pevent(&decoder, arg, prog);
			if (errcode < 0)
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:secondary") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:secondary: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.primary = 0;
			errcode = ptxed_sb_pevent(&decoder, arg, prog);
			if (errcode < 0)
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:sample-type") == 0) {
			if (!get_arg_uint64(&decoder.pevent.sample_type,
					    "--pevent:sample-type",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:time-zero") == 0) {
			if (!get_arg_uint64(&decoder.pevent.time_zero,
					    "--pevent:time-zero",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:time-shift") == 0) {
			if (!get_arg_uint16(&decoder.pevent.time_shift,
					    "--pevent:time-shift",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:time-mult") == 0) {
			if (!get_arg_uint32(&decoder.pevent.time_mult,
					    "--pevent:time-mult",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:tsc-offset") == 0) {
			if (!get_arg_uint64(&decoder.pevent.tsc_offset,
					    "--pevent:tsc-offset",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:kernel-start") == 0) {
			if (!get_arg_uint64(&decoder.pevent.kernel_start,
					    "--pevent:kernel-start",
					    argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--pevent:sysroot") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:sysroot: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.sysroot = arg;
			continue;
		}
#if defined(FEATURE_ELF)
		if (strcmp(arg, "--pevent:kcore") == 0) {
			struct pt_image *kernel;
			uint64_t base;

			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:kcore: "
					"missing argument.\n", prog);
				goto err;
			}

			base = 0ull;
			errcode = extract_base(arg, &base);
			if (errcode < 0)
				goto err;

			kernel = pt_sb_kernel_image(decoder.session);

			errcode = load_elf(decoder.iscache, kernel, arg, base,
					   prog, options.track_image);
			if (errcode < 0)
				goto err;

			continue;
		}
#endif /* defined(FEATURE_ELF) */
		if (strcmp(arg, "--pevent:vdso-x64") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:vdso-x64: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.vdso_x64 = arg;
			continue;
		}
		if (strcmp(arg, "--pevent:vdso-x32") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:vdso-x32: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.vdso_x32 = arg;
			continue;
		}
		if (strcmp(arg, "--pevent:vdso-ia32") == 0) {
			arg = argv[i++];
			if (!arg) {
				fprintf(stderr, "%s: --pevent:vdso-ia32: "
					"missing argument.\n", prog);
				goto err;
			}

			decoder.pevent.vdso_ia32 = arg;
			continue;
		}
#endif /* defined(FEATURE_PEVENT) */
#endif /* defined(FEATURE_SIDEBAND) */
		if (strcmp(arg, "--cpu") == 0) {
			/* override cpu information before the decoder
			 * is initialized.
			 */
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify cpu before the pt source file.\n",
					prog);
				goto err;
			}
			if (argc <= i) {
				fprintf(stderr,
					"%s: --cpu: missing argument.\n", prog);
				goto out;
			}
			arg = argv[i++];

			if (strcmp(arg, "auto") == 0) {
				errcode = pt_cpu_read(&config.cpu);
				if (errcode < 0) {
					fprintf(stderr,
						"%s: error reading cpu: %s.\n",
						prog,
						pt_errstr(pt_errcode(errcode)));
					return 1;
				}
				continue;
			}

			if (strcmp(arg, "none") == 0) {
				memset(&config.cpu, 0, sizeof(config.cpu));
				continue;
			}

			errcode = pt_cpu_parse(&config.cpu, arg);
			if (errcode < 0) {
				fprintf(stderr,
					"%s: cpu must be specified as f/m[/s]\n",
					prog);
				goto err;
			}
			continue;
		}
		if (strcmp(arg, "--mtc-freq") == 0) {
			if (!get_arg_uint8(&config.mtc_freq, "--mtc-freq",
					   argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--nom-freq") == 0) {
			if (!get_arg_uint8(&config.nom_freq, "--nom-freq",
					   argv[i++], prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--cpuid-0x15.eax") == 0) {
			if (!get_arg_uint32(&config.cpuid_0x15_eax,
					    "--cpuid-0x15.eax", argv[i++],
					    prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--cpuid-0x15.ebx") == 0) {
			if (!get_arg_uint32(&config.cpuid_0x15_ebx,
					    "--cpuid-0x15.ebx", argv[i++],
					    prog))
				goto err;

			continue;
		}
		if (strcmp(arg, "--verbose") == 0 || strcmp(arg, "-v") == 0) {
			options.track_image = 1;
			continue;
		}

		if (strcmp(arg, "--insn-decoder") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before the pt "
					"source file.\n", arg, prog);
				goto err;
			}

			decoder.type = pdt_insn_decoder;
			continue;
		}

		if (strcmp(arg, "--insn:keep-tcal-on-ovf") == 0) {
			decoder.insn.flags.variant.insn.keep_tcal_on_ovf = 1;
			continue;
		}


		if (strcmp(arg, "--block-decoder") == 0) {
			if (ptxed_have_decoder(&decoder)) {
				fprintf(stderr,
					"%s: please specify %s before the pt "
					"source file.\n", arg, prog);
				goto err;
			}

			decoder.type = pdt_block_decoder;
			continue;
		}

		if (strcmp(arg, "--block:show-blocks") == 0) {
			options.track_blocks = 1;
			continue;
		}

		if (strcmp(arg, "--block:end-on-call") == 0) {
			decoder.block.flags.variant.block.end_on_call = 1;
			continue;
		}

		if (strcmp(arg, "--block:end-on-jump") == 0) {
			decoder.block.flags.variant.block.end_on_jump = 1;
			continue;
		}

		if (strcmp(arg, "--block:keep-tcal-on-ovf") == 0) {
			decoder.block.flags.variant.block.keep_tcal_on_ovf = 1;
			continue;
		}

		fprintf(stderr, "%s: unknown option: %s.\n", prog, arg);
		goto err;
	}

	if (!ptxed_have_decoder(&decoder)) {
		fprintf(stderr, "%s: no pt file.\n", prog);
		goto err;
	}

	xed_tables_init();

	/* If we didn't select any statistics, select them all depending on the
	 * decoder type.
	 */
	if (options.print_stats && !stats.flags) {
		stats.flags |= ptxed_stat_insn;

		if (decoder.type == pdt_block_decoder)
			stats.flags |= ptxed_stat_blocks;
	}

#if defined(FEATURE_SIDEBAND)
	errcode = pt_sb_init_decoders(decoder.session);
	if (errcode < 0) {
		fprintf(stderr,
			"%s: error initializing sideband decoders: %s.\n",
			prog, pt_errstr(pt_errcode(errcode)));
		goto err;
	}
#endif /* defined(FEATURE_SIDEBAND) */

	decode(&decoder, &options, options.print_stats ? &stats : NULL);

	if (options.print_stats)
		print_stats(&stats);

out:
	ptxed_free_decoder(&decoder);
	pt_image_free(image);
	free(config.begin);
	return 0;

err:
	ptxed_free_decoder(&decoder);
	pt_image_free(image);
	free(config.begin);
	return 1;
}