aboutsummaryrefslogtreecommitdiffhomepage
path: root/print.html
blob: 438340449c79e1641e4b1167a36abe351734f86d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
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
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Notes</title>
        <meta name="robots" content="noindex" />


        <!-- Custom HTML head -->
        
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="intro.html">Introduction</a></li><li class="chapter-item expanded "><a href="tools/index.html"><strong aria-hidden="true">1.</strong> Tools</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="tools/zsh.html"><strong aria-hidden="true">1.1.</strong> zsh</a></li><li class="chapter-item expanded "><a href="tools/bash.html"><strong aria-hidden="true">1.2.</strong> bash</a></li><li class="chapter-item expanded "><a href="tools/fish.html"><strong aria-hidden="true">1.3.</strong> fish</a></li><li class="chapter-item expanded "><a href="tools/tmux.html"><strong aria-hidden="true">1.4.</strong> tmux</a></li><li class="chapter-item expanded "><a href="tools/git.html"><strong aria-hidden="true">1.5.</strong> git</a></li><li class="chapter-item expanded "><a href="tools/awk.html"><strong aria-hidden="true">1.6.</strong> awk</a></li><li class="chapter-item expanded "><a href="tools/emacs.html"><strong aria-hidden="true">1.7.</strong> emacs</a></li><li class="chapter-item expanded "><a href="tools/gpg.html"><strong aria-hidden="true">1.8.</strong> gpg</a></li><li class="chapter-item expanded "><a href="tools/gdb.html"><strong aria-hidden="true">1.9.</strong> gdb</a></li><li class="chapter-item expanded "><a href="tools/gdbserver.html"><strong aria-hidden="true">1.10.</strong> gdbserver</a></li><li class="chapter-item expanded "><a href="tools/radare2.html"><strong aria-hidden="true">1.11.</strong> radare2</a></li><li class="chapter-item expanded "><a href="tools/qemu.html"><strong aria-hidden="true">1.12.</strong> qemu</a></li><li class="chapter-item expanded "><a href="tools/pacman.html"><strong aria-hidden="true">1.13.</strong> pacman</a></li><li class="chapter-item expanded "><a href="tools/dot.html"><strong aria-hidden="true">1.14.</strong> dot</a></li></ol></li><li class="chapter-item expanded "><a href="monitor/index.html"><strong aria-hidden="true">2.</strong> Resource analysis & monitor</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="monitor/lsof.html"><strong aria-hidden="true">2.1.</strong> lsof</a></li><li class="chapter-item expanded "><a href="monitor/ss.html"><strong aria-hidden="true">2.2.</strong> ss</a></li><li class="chapter-item expanded "><a href="monitor/pidstat.html"><strong aria-hidden="true">2.3.</strong> pidstat</a></li><li class="chapter-item expanded "><a href="monitor/pgrep.html"><strong aria-hidden="true">2.4.</strong> pgrep</a></li><li class="chapter-item expanded "><a href="monitor/pmap.html"><strong aria-hidden="true">2.5.</strong> pmap</a></li><li class="chapter-item expanded "><a href="monitor/pstack.html"><strong aria-hidden="true">2.6.</strong> pstack</a></li></ol></li><li class="chapter-item expanded "><a href="trace_profile/index.html"><strong aria-hidden="true">3.</strong> Trace and Profile</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="trace_profile/strace.html"><strong aria-hidden="true">3.1.</strong> strace</a></li><li class="chapter-item expanded "><a href="trace_profile/ltrace.html"><strong aria-hidden="true">3.2.</strong> ltrace</a></li><li class="chapter-item expanded "><a href="trace_profile/perf.html"><strong aria-hidden="true">3.3.</strong> perf</a></li><li class="chapter-item expanded "><a href="trace_profile/oprofile.html"><strong aria-hidden="true">3.4.</strong> OProfile</a></li><li class="chapter-item expanded "><a href="trace_profile/time.html"><strong aria-hidden="true">3.5.</strong> time</a></li></ol></li><li class="chapter-item expanded "><a href="binary/index.html"><strong aria-hidden="true">4.</strong> Binary</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="binary/od.html"><strong aria-hidden="true">4.1.</strong> od</a></li><li class="chapter-item expanded "><a href="binary/xxd.html"><strong aria-hidden="true">4.2.</strong> xxd</a></li><li class="chapter-item expanded "><a href="binary/readelf.html"><strong aria-hidden="true">4.3.</strong> readelf</a></li><li class="chapter-item expanded "><a href="binary/objdump.html"><strong aria-hidden="true">4.4.</strong> objdump</a></li><li class="chapter-item expanded "><a href="binary/nm.html"><strong aria-hidden="true">4.5.</strong> nm</a></li></ol></li><li class="chapter-item expanded "><a href="development/index.html"><strong aria-hidden="true">5.</strong> Development</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/c++filt.html"><strong aria-hidden="true">5.1.</strong> c++filt</a></li><li class="chapter-item expanded "><a href="development/c++.html"><strong aria-hidden="true">5.2.</strong> c++</a></li><li class="chapter-item expanded "><a href="development/glibc.html"><strong aria-hidden="true">5.3.</strong> glibc</a></li><li class="chapter-item expanded "><a href="development/gcc.html"><strong aria-hidden="true">5.4.</strong> gcc</a></li><li class="chapter-item expanded "><a href="development/make.html"><strong aria-hidden="true">5.5.</strong> make</a></li><li class="chapter-item expanded "><a href="development/ld.so.html"><strong aria-hidden="true">5.6.</strong> ld.so</a></li><li class="chapter-item expanded "><a href="development/symbolver.html"><strong aria-hidden="true">5.7.</strong> symbol versioning</a></li><li class="chapter-item expanded "><a href="development/python.html"><strong aria-hidden="true">5.8.</strong> python</a></li></ol></li><li class="chapter-item expanded "><a href="linux/index.html"><strong aria-hidden="true">6.</strong> Linux</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="linux/systemd.html"><strong aria-hidden="true">6.1.</strong> systemd</a></li><li class="chapter-item expanded "><a href="linux/coredump.html"><strong aria-hidden="true">6.2.</strong> coredump</a></li><li class="chapter-item expanded "><a href="linux/ptrace_scope.html"><strong aria-hidden="true">6.3.</strong> ptrace_scope</a></li><li class="chapter-item expanded "><a href="linux/cryptsetup.html"><strong aria-hidden="true">6.4.</strong> cryptsetup</a></li><li class="chapter-item expanded "><a href="linux/swap.html"><strong aria-hidden="true">6.5.</strong> swap</a></li><li class="chapter-item expanded "><a href="linux/input.html"><strong aria-hidden="true">6.6.</strong> input</a></li></ol></li><li class="chapter-item expanded "><a href="network/index.html"><strong aria-hidden="true">7.</strong> Network</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="network/tcpdump.html"><strong aria-hidden="true">7.1.</strong> tcpdump</a></li><li class="chapter-item expanded "><a href="network/firewall-cmd.html"><strong aria-hidden="true">7.2.</strong> firewall-cmd</a></li><li class="chapter-item expanded "><a href="network/nftables.html"><strong aria-hidden="true">7.3.</strong> nftables</a></li></ol></li><li class="chapter-item expanded "><a href="web/index.html"><strong aria-hidden="true">8.</strong> Web</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="web/html.html"><strong aria-hidden="true">8.1.</strong> html</a></li><li class="chapter-item expanded "><a href="web/chartjs.html"><strong aria-hidden="true">8.2.</strong> chartjs</a></li></ol></li><li class="chapter-item expanded "><a href="arch/index.html"><strong aria-hidden="true">9.</strong> Arch</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="arch/x86_64.html"><strong aria-hidden="true">9.1.</strong> x86_64</a></li><li class="chapter-item expanded "><a href="arch/arm64.html"><strong aria-hidden="true">9.2.</strong> arm64</a></li><li class="chapter-item expanded "><a href="arch/armv7.html"><strong aria-hidden="true">9.3.</strong> armv7</a></li><li class="chapter-item expanded "><a href="arch/riscv.html"><strong aria-hidden="true">9.4.</strong> riscv</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Notes</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        <a href="https://github.com/johannst/notes" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="notes"><a class="header" href="#notes">Notes</a></h1>
<p>A personal collection of notes and cheatsheets.</p>
<p>Source code is located at <a href="https://github.com/johannst/notes">johannst/notes</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="tools"><a class="header" href="#tools">Tools</a></h1>
<ul>
<li><a href="tools/./zsh.html">zsh</a></li>
<li><a href="tools/./bash.html">bash</a></li>
<li><a href="tools/./fish.html">fish</a></li>
<li><a href="tools/./tmux.html">tmux</a></li>
<li><a href="tools/./git.html">git</a></li>
<li><a href="tools/./awk.html">awk</a></li>
<li><a href="tools/./emacs.html">emacs</a></li>
<li><a href="tools/./gpg.html">gpg</a></li>
<li><a href="tools/./gdb.html">gdb</a></li>
<li><a href="tools/./gdbserver.html">gdbserver</a></li>
<li><a href="tools/./radare2.html">radare2</a></li>
<li><a href="tools/./qemu.html">qemu</a></li>
<li><a href="tools/./pacman.html">pacman</a></li>
<li><a href="tools/./dot.html">dot</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="zsh1"><a class="header" href="#zsh1">zsh(1)</a></h1>
<h2 id="keybindings"><a class="header" href="#keybindings">Keybindings</a></h2>
<p>Change input mode:</p>
<pre><code class="language-zsh">bindkey -v              change to vi keymap
bindkey -e              change to emacs keymap
</code></pre>
<p>Define key-mappings:</p>
<pre><code class="language-zsh">bindkey                 list mappings in current keymap
bindkey in-str cmd      create mapping for `in-str` to `cmd`
bindkey -r in-str       remove binding for `in-str`

# C-v &lt;key&gt;             dump &lt;key&gt; code, which can be used in `in-str`
# zle -l                list all functions for keybindings
# man zshzle(1)         STANDARD WIDGETS: get description of functions
</code></pre>
<p>Access edit buffer in zle widget:</p>
<pre><code class="language-zsh">$BUFFER       # Entire edit buffer content
$LBUFFER      # Edit buffer content left to cursor
$RBUFFER      # Edit buffer content right to cursor

# create zle widget which adds text right of the cursor
function add-text() {
    RBUFFER=&quot;some text $RBUFFER&quot;
}
zle -N add-text

bindkey &quot;^p&quot; add-text
</code></pre>
<h2 id="parameter"><a class="header" href="#parameter">Parameter</a></h2>
<p>Default value:</p>
<pre><code class="language-zsh"># default value
echo ${foo:-defval}   # defval
foo=bar
echo ${foo:-defval}   # bar
</code></pre>
<p>Alternative value:</p>
<pre><code class="language-zsh">echo ${foo:+altval}   # ''
foo=bar
echo ${foo:+altval}   # altval
</code></pre>
<p>Check variable set, error if not set:</p>
<pre><code class="language-zsh">echo ${foo:?msg}      # print `msg` and return errno `1`
foo=bar
echo ${foo:?msg}      # bar
</code></pre>
<p>Sub-string <code>${var:offset:length}</code>:</p>
<pre><code class="language-zsh">foo=abcdef
echo ${foo:1:3}       # bcd
</code></pre>
<p>Trim prefix <code>${var#prefix}</code>:</p>
<pre><code class="language-zsh">foo=bar.baz
echo ${foo#bar}       # .baz
</code></pre>
<p>Trim suffix <code>${var%suffix}</code>:</p>
<pre><code class="language-zsh">foo=bar.baz
echo ${foo%.baz}      # bar
</code></pre>
<p>Substitute pattern <code>${var/pattern/replace}</code>:</p>
<pre><code class="language-zsh">foo=aabbccbbdd
echo ${foo/bb/XX}    # aaXXccbbdd
echo ${foo//bb/XX}   # aaXXccXXdd
# replace prefix
echo ${foo/#bb/XX}   # aabbccbbdd
echo ${foo/#aa/XX}   # XXbbccbbdd
# replace suffix
echo ${foo/%bb/XX}   # aabbccbbdd
echo ${foo/%dd/XX}   # aabbccbbXX
</code></pre>
<blockquote>
<p>Note: <code>prefix</code>/<code>suffix</code>/<code>pattern</code> are expanded as pathnames.</p>
</blockquote>
<h2 id="variables"><a class="header" href="#variables">Variables</a></h2>
<pre><code class="language-zsh"># Variable with local scope
local var=val

# Read-only variable
readonly var=bal
</code></pre>
<p>Indexed arrays:</p>
<pre><code class="language-zsh">arr=(aa bb cc dd)
echo $arr[1]           # aa
echo $arr[-1]          # dd

arr+=(ee)
echo $arr[-1]          # ee

echo $arr[1,3]         # aa bb cc
</code></pre>
<p>Associative arrays:</p>
<pre><code class="language-zsh">typeset -A arr
arr[x]='aa'
arr[y]='bb'
echo $arr[x]           # aa
</code></pre>
<p>Tied arrays:</p>
<pre><code class="language-zsh">typeset -T VEC vec=(1 2 3) '|'

echo $vec              # 1 2 3
echo $VEC              # 1|2|3
</code></pre>
<p>Unique arrays (set):</p>
<pre><code>typeset -U vec=(1 2 3)

echo $vec             # 1 2 3
vec+=(1 2 4)
echo $vec             # 1 2 3 4
</code></pre>
<h3 id="expansion-flags"><a class="header" href="#expansion-flags">Expansion Flags</a></h3>
<p>Join array to string <code>j:sep:</code>:</p>
<pre><code class="language-zsh">foo=(1 2 3 4)
echo ${(j:-:)foo}     # 1-2-3-4
echo ${(j:\n:)foo}    # join with new lines
</code></pre>
<p>Split string to array <code>s:sep</code>:</p>
<pre><code class="language-zsh">foo='1-2-3-4'
bar=(${(s:-:)foo})    # capture as array
echo $bar             # 1 2 3 4
echo $bar[2]          # 2
</code></pre>
<p>Upper/Lower case string:</p>
<pre><code class="language-zsh">foo=aaBB
echo ${(L)foo}        # aabb
echo ${(U)foo}        # AABB
</code></pre>
<p>Key/values in associative arrays:</p>
<pre><code class="language-zsh">typeset -A vec; vec[a]='aa'; vec[b]='bb'

echo ${(k)vec}        # a b
echo ${(v)vec}        # aa bb
echo ${(kv)vec}       # a aa b bb

# Iterate over key value pairs.
for k v in ${(kv)vec)}; do ...; done
</code></pre>
<h2 id="argument-parsing-with-zparseopts"><a class="header" href="#argument-parsing-with-zparseopts">Argument parsing with <code>zparseopts</code></a></h2>
<pre><code class="language-zsh">zparseopts [-D] [-E] [-A assoc] specs
</code></pre>
<p>Arguments are copied into the associative array <code>assoc</code> according to <code>specs</code>.
Each spec is described by an entry as <code>opt[:][=array]</code>.</p>
<ul>
<li><code>opt</code> is the option without the <code>-</code> char. Passing <code>-f</code> is matched against <code>f</code>
opt, <code>--long</code> is matched against <code>-long</code>.</li>
<li>Using <code>:</code> means the option will take an argument.</li>
<li>The optional <code>=array</code> specifies an alternate storage container where this
option should be stored.</li>
</ul>
<blockquote>
<p>Documentation can be found in <code>man zshmodules</code>.</p>
</blockquote>
<h3 id="example"><a class="header" href="#example">Example</a></h3>
<pre><code class="language-zsh">#!/bin/zsh
function test() {
    zparseopts -D -E -A opts f=flag o: -long:
    echo &quot;flag $flag&quot;
    echo &quot;o    $opts[-o]&quot;
    echo &quot;long $opts[--long]&quot;
    echo &quot;pos  $1&quot;
}

test -f -o OPTION --long LONG_OPT POSITIONAL

# Outputs:
#   flag -f
#   o    OPTION
#   long LONG_OPT
#   pos  POSITIONAL
</code></pre>
<h2 id="regular-expressions"><a class="header" href="#regular-expressions">Regular Expressions</a></h2>
<p>Zsh supports regular expression matching with the binary operator <code>=~</code>.
The match results can be accessed via the <code>$MATCH</code> variable and
<code>$match</code> indexed array:</p>
<ul>
<li><code>$MATCH</code> contains the full match</li>
<li><code>$match[1]</code> contains match of the first capture group</li>
</ul>
<pre><code class="language-zsh">INPUT='title foo : 1234'
REGEX='^title (.+) : ([0-9]+)$'
if [[ $INPUT =~ $REGEX ]]; then
    echo &quot;$MATCH&quot;       # title foo : 1234
    echo &quot;$match[1]&quot;    # foo
    echo &quot;$match[2]&quot;    # 1234
fi
</code></pre>
<h2 id="completion"><a class="header" href="#completion">Completion</a></h2>
<h3 id="installation"><a class="header" href="#installation">Installation</a></h3>
<p>Completion functions are provided via files and need to be placed in a location
covered by <code>$fpath</code>. By convention the completion files are names as <code>_&lt;CMD&gt;</code>.</p>
<p>A completion skeleton for the command <code>foo</code>, stored in <code>_foo</code></p>
<pre><code class="language-zsh">#compdef _foo foo

function _foo() {
    ...
}
</code></pre>
<p>Alternatively one can install a completion function explicitly by calling <code>compdef &lt;FUNC&gt; &lt;CMD&gt;</code>.</p>
<h3 id="completion-variables"><a class="header" href="#completion-variables">Completion Variables</a></h3>
<p>Following variables are available in Completion functions:</p>
<pre><code class="language-zsh">$words              # array with command line in words
$#words             # number words
$CURRENT            # index into $words for cursor position
$words[CURRENT-1]   # previous word (relative to cursor position)
</code></pre>
<h3 id="completion-functions"><a class="header" href="#completion-functions">Completion Functions</a></h3>
<ul>
<li><code>_describe</code>     simple completion, just words + description</li>
<li><code>_arguments</code>    sophisticated completion, allow to specify actions</li>
</ul>
<h4 id="completion-with-_describe"><a class="header" href="#completion-with-_describe">Completion with <a href="http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions"><code>_describe</code></a></a></h4>
<pre><code class="language-zsh">_describe MSG COMP
</code></pre>
<ul>
<li><code>MSG</code> simple string with header message</li>
<li><code>COMP</code> array of completions where each entry is <code>&quot;opt:description&quot;</code></li>
</ul>
<pre><code class="language-zsh">function _foo() {
    local -a opts
    opts=('bla:desc for bla' 'blu:desc for blu')
    _describe 'foo-msg' opts
}
compdef _foo foo

foo &lt;TAB&gt;&lt;TAB&gt;
 -- foo-msg --
bla  -- desc for bla
blu  -- desc for blu
</code></pre>
<h4 id="completion-with-_arguments"><a class="header" href="#completion-with-_arguments">Completion with <a href="http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions"><code>_arguments</code></a></a></h4>
<pre><code class="language-zsh">_arguments SPEC [SPEC...]
</code></pre>
<p>where <code>SPEC</code> can have one of the following forms:</p>
<ul>
<li><code>OPT[DESC]:MSG:ACTION</code></li>
<li><code>N:MSG:ACTION</code></li>
</ul>
<p>Available actions</p>
<pre><code class="language-zsh">(op1 op2)   list possible matches
-&gt;VAL       set $state=VAL and continue, `$state` can be checked later in switch case
FUNC        call func to generate matches
{STR}       evaluate `STR` to generate matches
</code></pre>
<h3 id="example-1"><a class="header" href="#example-1">Example</a></h3>
<p>Skeleton to copy/paste for writing simple completions.</p>
<p>Assume a program <code>foo</code> with the following interface:</p>
<pre><code class="language-zsh">foo -c green|red|blue -s low|high -f &lt;file&gt; -d &lt;dir&gt; -h
</code></pre>
<p>The completion handler could be implemented as follows in a file called <code>_foo</code>:</p>
<pre><code class="language-zsh">#compdef _foo foo

function _foo_color() {
    local colors=()
    colors+=('green:green color')
    colors+=('red:red color')
    colors+=('blue:blue color')
    _describe &quot;color&quot; colors
}

function _foo() {
    _arguments                              \
        &quot;-c[define color]:color:-&gt;s_color&quot;  \
        &quot;-s[select sound]:sound:(low high)&quot; \
        &quot;-f[select file]:file:_files&quot;       \
        &quot;-d[select dir]:dir:_files -/&quot;      \
        &quot;-h[help]&quot;

    case $state in
        s_color) _foo_color;;
    esac
}
</code></pre>
<blockquote>
<p><code>_files</code> is a zsh builtin utility function to complete files/dirs see</p>
<ul>
<li><a href="http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions">zsh completion functions</a></li>
<li><a href="https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org#utility-functions">zsh completion utility functions</a></li>
</ul>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="bash1"><a class="header" href="#bash1">bash(1)</a></h1>
<h2 id="expansion"><a class="header" href="#expansion">Expansion</a></h2>
<h3 id="generator"><a class="header" href="#generator">Generator</a></h3>
<pre><code class="language-bash"># generate sequence from n to m
{n..m}
# generate sequence from n to m step by s
{n..m..s}

# expand cartesian product
{a,b}{c,d}
</code></pre>
<h3 id="parameter-1"><a class="header" href="#parameter-1">Parameter</a></h3>
<pre><code class="language-bash"># default value
bar=${foo:-some_val}  # if $foo set, then bar=$foo else bar=some_val

# alternate value
bar=${foo:+bla $foo}  # if $foo set, then bar=&quot;bla $foo&quot; else bar=&quot;&quot;

# check param set
bar=${foo:?msg}  # if $foo set, then bar=$foo else exit and print msg

# indirect
FOO=foo
BAR=FOO
bar=${!BAR}  # deref value of BAR -&gt; bar=$FOO

# prefix
${foo#prefix}  # remove prefix when expanding $foo
# suffix
${foo%suffix}  # remove suffix when expanding $foo

# substitute
${foo/pattern/string}  # replace pattern with string when expanding foo
# pattern starts with
# '/'   replace all occurences of pattern
# '#'   pattern match at beginning
# '%'   pattern match at end
</code></pre>
<blockquote>
<p>Note: <code>prefix</code>/<code>suffix</code>/<code>pattern</code> are expanded as <a href="tools/bash.html#pathname">pathnames</a>.</p>
</blockquote>
<h3 id="pathname"><a class="header" href="#pathname">Pathname</a></h3>
<pre><code class="language-bash">*           match any string
?           match any single char
\\          match backslash
[abc]       match any char of 'a' 'b' 'c'
[a-z]       match any char between 'a' - 'z'
[^ab]       negate, match all not 'a' 'b'
[:class:]   match any char in class, available:
              alnum,alpha,ascii,blank,cntrl,digit,graph,lower,
              print,punct,space,upper,word,xdigit
</code></pre>
<p>With <code>extglob</code> shell option enabled it is possible to have more powerful
patterns. In the following <code>pattern-list</code> is one ore more patterns separated
by <code>|</code> char.</p>
<pre><code class="language-bash">?(pattern-list)   matches zero or one occurrence of the given patterns
*(pattern-list)   matches zero or more occurrences of the given patterns
+(pattern-list)   matches one or more occurrences of the given patterns
@(pattern-list)   matches one of the given patterns
!(pattern-list)   matches anything except one of the given patterns
</code></pre>
<blockquote>
<p>Note: <code>shopt -s extglob</code>/<code>shopt -u extglob</code> to enable/disable <code>extglob</code>
option.</p>
</blockquote>
<h2 id="io-redirection"><a class="header" href="#io-redirection">I/O redirection</a></h2>
<blockquote>
<p>Note: The trick with bash I/O redirection is to interpret from left-to-right.</p>
</blockquote>
<pre><code class="language-bash"># stdout &amp; stderr to file
command &gt;file 2&gt;&amp;1
# equivalent
command &amp;&gt;file

# stderr to stdout &amp; stdout to file
command 2&gt;&amp;1 &gt;file
</code></pre>
<blockquote>
<p>The article <a href="https://catonmat.net/bash-one-liners-explained-part-three">Bash One-Liners Explained, Part III: All about
redirections</a>
contains some nice visualization to explain bash redirections.</p>
</blockquote>
<h3 id="explanation"><a class="header" href="#explanation">Explanation</a></h3>
<pre><code class="language-bash">j&gt;&amp;i
</code></pre>
<p>Duplicate <code>fd i</code> to <code>fd j</code>, making <code>j</code> a copy of <code>i</code>. See <a href="http://man7.org/linux/man-pages/man2/dup.2.html">dup2(2)</a>.</p>
<p>Example:</p>
<pre><code class="language-bash">command 2&gt;&amp;1 &gt;file
</code></pre>
<ol>
<li>duplicate <code>fd 1</code> to <code>fd 2</code>, effectively redirecting <code>stderr</code> to <code>stdout</code></li>
<li>redirect <code>stdout</code> to <code>file</code></li>
</ol>
<h2 id="argument-parsing-with-getopts"><a class="header" href="#argument-parsing-with-getopts">Argument parsing with <code>getopts</code></a></h2>
<p>The <code>getopts</code> builtin uses following global variables:</p>
<ul>
<li><code>OPTARG</code>, value of last option argument</li>
<li><code>OPTIND</code>, index of the next argument to process (user must reset)</li>
<li><code>OPTERR</code>, display errors if set to <code>1</code></li>
</ul>
<pre><code class="language-bash">getopts &lt;optstring&gt; &lt;param&gt; [&lt;args&gt;]
</code></pre>
<ul>
<li><code>&lt;optstring&gt;</code> specifies the names of supported options, eg <code>f:c</code>
<ul>
<li><code>f:</code> means <code>-f</code> option with an argument</li>
<li><code>c</code> means <code>-c</code> option without an argument</li>
</ul>
</li>
<li><code>&lt;param&gt;</code> specifies a variable name which <code>getopts</code> fills with the last parsed option argument</li>
<li><code>&lt;args&gt;</code> optionally specify argument string to parse, by default <code>getopts</code> parses <code>$@</code></li>
</ul>
<h3 id="example-2"><a class="header" href="#example-2">Example</a></h3>
<pre><code class="language-bash">#!/bin/bash
function parse_args() {
    while getopts &quot;f:c&quot; PARAM; do
        case $PARAM in
            f) echo &quot;GOT -f $OPTARG&quot;;;
            c) echo &quot;GOT -c&quot;;;
            *) echo &quot;ERR: print usage&quot;; exit 1;;
        esac
    done
    # users responsibility to reset OPTIND
    OPTIND=1
}

parse_args -f xxx -c
parse_args -f yyy
</code></pre>
<h2 id="regular-expressions-1"><a class="header" href="#regular-expressions-1">Regular Expressions</a></h2>
<p>Bash supports regular expression matching with the binary operator <code>=~</code>.
The match results can be accessed via the <code>$BASH_REMATCH</code> variable:</p>
<ul>
<li><code>${BASH_REMATCH[0]}</code> contains the full match</li>
<li><code>${BASH_REMATCH[1]}</code> contains match of the first capture group</li>
</ul>
<pre><code class="language-bash">INPUT='title foo : 1234'
REGEX='^title (.+) : ([0-9]+)$'
if [[ $INPUT =~ $REGEX ]]; then
    echo &quot;${BASH_REMATCH[0]}&quot;    # title foo : 1234
    echo &quot;${BASH_REMATCH[1]}&quot;    # foo
    echo &quot;${BASH_REMATCH[2]}&quot;    # 1234
fi
</code></pre>
<blockquote>
<p><strong>Caution</strong>: When specifying a <code>regex</code> in the <code>[[ ]]</code> block directly, quotes will be treated as part of the pattern.
<code>[[ $INPUT =~ &quot;foo&quot; ]]</code> will match against <code>&quot;foo&quot;</code> not <code>foo</code>!</p>
</blockquote>
<h2 id="completion-1"><a class="header" href="#completion-1">Completion</a></h2>
<p>The <code>complete</code> builtin is used to interact with the completion system.</p>
<pre><code class="language-bash">complete                    # print currently installed completion handler
complete -F &lt;func&gt; &lt;cmd&gt;    # install &lt;func&gt; as completion handler for &lt;cmd&gt;
complete -r &lt;cmd&gt;           # uninstall completion handler for &lt;cmd&gt;
</code></pre>
<p>Variables available in completion functions:</p>
<pre><code class="language-bash"># in
$1              # &lt;cmd&gt;
$2              # current word
$3              # privous word

COMP_WORDS      # array with current command line words
COMP_CWORD      # index into COMP_WORDS with current cursor position

# out
COMPREPLY       # array with possible completions
</code></pre>
<p>The <code>compgen</code> builtin is used to generate possible matches by comparing <code>word</code>
against words generated by <code>option</code>.</p>
<pre><code class="language-bash">compgen &lt;option&gt; &lt;word&gt;

# usefule options:
# -W &lt;list&gt;    specify list of possible completions
# -d           generate list with dirs
# -f           generate list with files
# -u           generate list with users
# -e           generate list with exported variables

# compare &quot;f&quot; against words &quot;foo&quot; &quot;foobar&quot; &quot;bar&quot; and generate matches
compgen -W &quot;foo foobar bar&quot; &quot;f&quot;

# compare &quot;hom&quot; against file/dir names and generate matches
compgen -d -f &quot;hom&quot;
</code></pre>
<h3 id="example-3"><a class="header" href="#example-3">Example</a></h3>
<p>Skeleton to copy/paste for writing simple completions.</p>
<p>Assume a program <code>foo</code> with the following interface:</p>
<pre><code class="language-bash">foo -c green|red|blue -s low|high -f &lt;file&gt; -h
</code></pre>
<p>The completion handler could be implemented as follows:</p>
<pre><code class="language-bash">function _foo() {
    local curr=$2
    local prev=$3

    local opts=&quot;-c -s -f -h&quot;
    case $prev in
        -c) COMPREPLY=( $(compgen -W &quot;green red blue&quot; -- $curr) );;
        -s) COMPREPLY=( $(compgen -W &quot;low high&quot; -- $curr) );;
        -f) COMPREPLY=( $(compgen -f -- $curr) );;
        *)  COMPREPLY=( $(compgen -W &quot;$opts&quot; -- $curr) );;
    esac
}

complete -F _foo foo
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="fish1"><a class="header" href="#fish1">fish(1)</a></h1>
<h2 id="quick-info"><a class="header" href="#quick-info">Quick Info</a></h2>
<p>Fish initialization file <code>~/.config/fish/config.fish</code></p>
<p>Switch between different key bindings:</p>
<ul>
<li><code>fish_default_key_bindings</code> to use default key bindings</li>
<li><code>fish_vi_key_bindings</code> to use vi key bindings</li>
</ul>
<h2 id="variables-1"><a class="header" href="#variables-1">Variables</a></h2>
<p>Available scopes</p>
<ul>
<li><code>local</code> variable local to a block</li>
<li><code>global</code> variable global to shell instance</li>
<li><code>universal</code> variable universal to all shell instances + preserved across
shell restart</li>
</ul>
<h3 id="setunset-variables"><a class="header" href="#setunset-variables">Set/Unset Variables</a></h3>
<pre><code class="language-text">set &lt;name&gt; [&lt;values&gt;]
    -l  local scope
    -g  global scope
    -U  universal scope
    -e  erase variable
    -S  show verbose info
    -x  export to ENV
    -u  unexport from ENV
</code></pre>
<h3 id="lists"><a class="header" href="#lists">Lists</a></h3>
<p>In <code>fish</code> all variables are lists (start with index <code>1</code>, but lists can't
contain lists.</p>
<pre><code class="language-text">set foo a b c d

echo $foo[1]      # a
echo $foo[-1]     # d
echo $foo[2..3]   # b c
echo $foo[1 3]    # a c
</code></pre>
<p><code>$</code> can be seen as dereference operator.</p>
<pre><code class="language-text">set foo a; set a 1337
echo $$foo  # outputs 1337
</code></pre>
<p>Cartesian product.</p>
<pre><code class="language-text">echo file.{h,cc}
# file.h file.cc

echo {a,b}{1,2}
# a1 b1 b2
</code></pre>
<h3 id="special-variables-lists"><a class="header" href="#special-variables-lists">Special Variables (Lists)</a></h3>
<pre><code class="language-text">$status      # exit code of last command
$pipestatus  # list of exit codes of pipe chain

$CMD_DURATION   # runtime of last command in ms
</code></pre>
<h4 id="path"><a class="header" href="#path"><code>*PATH</code></a></h4>
<p>Lists ending with <code>PATH</code> are automatically split at <code>:</code> when used and joined
with <code>:</code> when exported to the environment.</p>
<pre><code class="language-text">set -x BLA_PATH a:b:c:d
echo $BLA_PATH              # a b c d
env | grep BLA_PATH         # BLA_PATH=a:b:c:d
</code></pre>
<h2 id="command-handling"><a class="header" href="#command-handling">Command Handling</a></h2>
<pre><code class="language-text"># sub-commands are not run in quotes
echo &quot;ls output: &quot;(ls)
</code></pre>
<h3 id="io-redirection-1"><a class="header" href="#io-redirection-1">I/O redirection</a></h3>
<pre><code class="language-text"># 'noclobber', fail if 'log' already exists
echo foo &gt;? log
</code></pre>
<h2 id="control-flow"><a class="header" href="#control-flow">Control Flow</a></h2>
<h3 id="if--else"><a class="header" href="#if--else"><code>if</code> / <code>else</code></a></h3>
<pre><code class="language-text">if grep foo bar
    # do sth
else if grep foobar bar
    # do sth else
else
    # do sth else
end
</code></pre>
<h3 id="switch"><a class="header" href="#switch"><code>switch</code></a></h3>
<pre><code class="language-text">switch (echo foo)
case 'foo*'
    # do start with foo
case bar dudel
    # do bar and dudel
case '*'
    # do else
end
</code></pre>
<h3 id="while-loop"><a class="header" href="#while-loop"><code>while</code> Loop</a></h3>
<pre><code class="language-text">while true
    echo foo
end
</code></pre>
<h3 id="for-loop"><a class="header" href="#for-loop"><code>for</code> Loop</a></h3>
<pre><code class="language-text">for f in (ls)
    echo $f
end
</code></pre>
<h2 id="functions"><a class="header" href="#functions">Functions</a></h2>
<p>Function arguments are passed via <code>$argv</code> list.</p>
<pre><code class="language-text">function fn_foo
    echo $argv
end
</code></pre>
<h3 id="autoloading"><a class="header" href="#autoloading">Autoloading</a></h3>
<p>When running a command fish attempts to autoload a function. The shell looks
for <code>&lt;cmd&gt;.fish</code> in the locations defined by <code>$fish_function_path</code> and loads
the function lazily if found.</p>
<p>This is the preferred way over monolithically defining all functions in a
startup script.</p>
<h3 id="helper"><a class="header" href="#helper">Helper</a></h3>
<pre><code class="language-text">functions         # list al functions
functions foo     # describe function 'foo'
functions -e foo  # erase function 'foo'

funced foo        # edit function 'foo'
                  # '-e vim' to edit in vim
</code></pre>
<h2 id="prompt"><a class="header" href="#prompt">Prompt</a></h2>
<p>The prompt is defined by the output of the <code>fish_prompt</code> function.</p>
<pre><code class="language-text">function fish_prompt
    set -l cmd_ret
    echo &quot;&gt; &quot;(pwd) $cmd_ret&quot; &quot;
end
</code></pre>
<blockquote>
<p>Use <code>set_color</code> to manipulate terminal colors.</p>
</blockquote>
<h2 id="useful-builtins"><a class="header" href="#useful-builtins">Useful Builtins</a></h2>
<pre><code class="language-text"># history
history search &lt;str&gt;   # search history for &lt;str&gt;
history merge          # merge histories from fish sessions

# list
count $var            # count elements in list

# string
string split SEP STRING
</code></pre>
<h2 id="keymaps"><a class="header" href="#keymaps">Keymaps</a></h2>
<pre><code class="language-text">  Shift-Tab ........... tab-completion with search
  Alt-Up / Alt-Down ... search history with token under the cursor
  Alt-l ............... list content of dir under cursor
  Alt-p ............... append '2&gt;&amp;1 | less;' to current cmdline
</code></pre>
<h2 id="debug"><a class="header" href="#debug">Debug</a></h2>
<pre><code class="language-text">  status print-stack-trace .. prints function stacktrace (can be used in scripts)
  breakpoint ................ halt script execution and gives shell (C-d | exit
                              to continue)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="tmux1"><a class="header" href="#tmux1">tmux(1)</a></h1>
<p>Terminology:</p>
<ul>
<li><code>session</code> is a collection of pseudo terminals which can have multiple
<code>windows</code></li>
<li><code>window</code> uses the entire screen and can be split into rectangular <code>panes</code></li>
<li><code>pane</code> is a single pseudo terminal instance</li>
</ul>
<h1 id="tmux-cli"><a class="header" href="#tmux-cli">Tmux cli</a></h1>
<pre><code class="language-markdown"># Session
tmux                        creates new session
tmux ls                     list running sessions
tmux kill-session -t &lt;s&gt;    kill running session &lt;s&gt;
tmux attach -t &lt;s&gt; [-d]     attach to session &lt;s&gt;, detach other clients [-d]
tmux detach -s &lt;s&gt;          detach all clients from session &lt;s&gt;

# Environment
tmux showenv -g             show global tmux environment variables
tmux setenv -g &lt;var&gt; &lt;val&gt;  set variable in global tmux env

# Misc
tmux source-file &lt;file&gt;     source config &lt;file&gt;
tmux lscm                   list available tmux commnds
tmux show -g                show global tmux options
tmux display &lt;msg&gt;          display message in tmux status line
</code></pre>
<h2 id="scripting"><a class="header" href="#scripting">Scripting</a></h2>
<pre><code class="language-markdown"># Session
tmux list-sessions -F '#S'           list running sessions, only IDs

# Window
tmux list-windows -F '#I' -t &lt;s&gt;     list window IDs for session &lt;s&gt;
tmux selectw -t &lt;s&gt;:&lt;w&gt;              select window &lt;w&gt; in session &lt;s&gt;

# Pane
tmux list-panes -F '#P' -t &lt;s&gt;:&lt;w&gt;   list pane IDs for window &lt;w&gt; in session &lt;s&gt;
tmux selectp -t &lt;s&gt;:&lt;w&gt;.&lt;p&gt;          select pane &lt;p&gt; in window &lt;w&gt; in session &lt;s&gt;

# Run commands
tmux send -t &lt;s&gt;:&lt;w&gt;.&lt;p&gt; &quot;ls&quot; C-m    send cmds/keys to pane
tmux run -t &lt;p&gt; &lt;sh-cmd&gt;             run shell command &lt;sh-cmd&gt; in background and report output on pane -t &lt;p&gt;
</code></pre>
<p>For example cycle through all panes in all windows in all sessions:</p>
<pre><code class="language-bash"># bash
for s in $(tmux list-sessions -F '#S'); do
    for w in $(tmux list-windows -F '#I' -t $s); do
        for p in $(tmux list-panes -F '#P' -t $s:$w); do
            echo $s:$w.$p
        done
    done
done
</code></pre>
<h1 id="bindings"><a class="header" href="#bindings">Bindings</a></h1>
<pre><code class="language-markdown">prefix d    detach from current session
prefix c    create new window
prefix w    open window list
prefix $    rename session
prefix ,    rename window
prefix .    move current window
</code></pre>
<p>Following bindings are specific to my <a href="https://github.com/johannst/dotfiles/blob/master/tmux.conf"><code>tmux.conf</code></a>:</p>
<pre><code class="language-markdown">C-s         prefix

# Panes
prefix s    horizontal split
prefix v    vertical split
prefix f    toggle maximize/minimize current pane

# Movement
prefix Tab  toggle between window

prefix h    move to pane left
prefix j    move to pane down
prefix k    move to pane up
prefix l    move to pane right

# Resize
prefix C-h  resize pane left
prefix C-j  resize pane down
prefix C-k  resize pane up
prefix C-l  resize pane right

# Copy/Paste
prefix C-v    enter copy mode
prefix C-p    paste yanked text
prefix C-b    open copy-buffer list

# In Copy Mode
v     enable visual mode
y     yank selected text
</code></pre>
<h1 id="command-mode"><a class="header" href="#command-mode">Command mode</a></h1>
<p>To enter command mode <code>prefix :</code>.</p>
<p>Some useful commands are:</p>
<pre><code class="language-markdown">setw synchronize-panes on/off       enables/disables synchronized input to all panes
list-keys -t vi-copy                list keymaps for vi-copy mode
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="git1"><a class="header" href="#git1">git(1)</a></h1>
<h2 id="working-areas"><a class="header" href="#working-areas">Working areas</a></h2>
<pre><code class="language-text">+-------------------+ --- stash -----&gt; +-------+
| working directory |                  | stash |  // Shelving area.
+-------------------+ &lt;-- stash pop -- +-------+
      |       ^
     add      |
      |     reset
      v       |
+-------------------+
|   staging area    |
+-------------------+
      |
    commit
      |
      v
+-------------------+
| local repository  |
+-------------------+
      |       ^
     push     |
      |     fetch /
      |      pull
      v       |
+-------------------+
| remote repository |
+-------------------+
</code></pre>
<h2 id="staging"><a class="header" href="#staging">Staging</a></h2>
<pre><code class="language-markdown">  git add -p [&lt;file&gt;] ............ partial staging (interactive)
</code></pre>
<h2 id="remote"><a class="header" href="#remote">Remote</a></h2>
<pre><code class="language-markdown">  git remote -v .................. list remotes verbose (with URLs)
  git remote show [-n] &lt;remote&gt; .. list info for &lt;remote&gt; (like remote HEAD,
                                   remote branches, tracking mapping)
</code></pre>
<h2 id="branching"><a class="header" href="#branching">Branching</a></h2>
<pre><code class="language-markdown">  git branch [-a] ................ list available branches; -a to include
                                   remote branches
  git branch -vv ................. list branch &amp; annotate with head sha1 &amp;
                                   remote tracking branch
  git branch &lt;bname&gt; ............. create local branch with name &lt;bname&gt;
  git branch -d &lt;bname&gt; .......... delete local branch with name &lt;bname&gt;
  git checkout &lt;bname&gt; ........... switch to branch with name &lt;bname&gt;
  git checkout --track &lt;branch&gt; .. start to locally track a remote branch

  # Remote

  git push -u origin &lt;rbname&gt; ........ push local branch to origin (or other
                                       remote), and setup &lt;rbname&gt; as tracking
                                       branch
  git push origin --delete &lt;rbname&gt; .. delete branch &lt;rbname&gt; from origin (or
                                       other remote)
</code></pre>
<h2 id="tags"><a class="header" href="#tags">Tags</a></h2>
<pre><code class="language-markdown">  git tag -a &lt;tname&gt; -m &quot;descr&quot; ........ creates an annotated tag (full object
                                         containing tagger, date, ...)
  git tag -l ........................... list available tags
  git checkout tag/&lt;tname&gt; ............. checkout specific tag
  git checkout tag/&lt;tname&gt; -b &lt;bname&gt; .. checkout specific tag in a new branch

  # Remote

  git push origin --tags .... push local tags to origin (or other remote)
</code></pre>
<h2 id="log--commit-history"><a class="header" href="#log--commit-history">Log &amp; Commit History</a></h2>
<pre><code class="language-markdown">  git log --oneline ......... shows log in single line per commit -&gt; alias for
                              '--pretty=oneline --abbrev-commit'
  git log --graph ........... text based graph of commit history
  git log --decorate ........ decorate log with REFs

  git log -p &lt;file&gt; ......... show commit history + diffs for &lt;file&gt;
  git log --oneline &lt;file&gt; .. show commit history for &lt;file&gt; in compact format
</code></pre>
<h2 id="diff--commit-info"><a class="header" href="#diff--commit-info">Diff &amp; Commit Info</a></h2>
<pre><code class="language-markdown">  git diff &lt;commit&gt;..&lt;commit&gt; [&lt;file&gt;] .... show changes between two arbitrary
                                            commits. If one &lt;commit&gt; is omitted
                                            it is if HEAD is specified.
  git diff -U$(wc -l &lt;file&gt;) &lt;file&gt; ....... shows complete file with diffs
                                            instead of usual diff snippets
  git diff --staged ....................... show diffs of staged files

  git show --stat &lt;commit&gt; ................ show files changed by &lt;commit&gt;
  git show &lt;commit&gt; [&lt;file&gt;] .............. show diffs for &lt;commit&gt;

  git git show &lt;commit&gt;:&lt;file&gt; ............ show &lt;file&gt; at &lt;commit&gt;
</code></pre>
<h2 id="patching"><a class="header" href="#patching">Patching</a></h2>
<pre><code class="language-markdown">  git format-patch &lt;opt&gt; &lt;since&gt;/&lt;revision range&gt;
    opt:
      -N ................... use [PATCH] instead [PATCH n/m] in subject when
                             generating patch description (for patches spanning
                             multiple commits)
      --start-number &lt;n&gt; ... start output file generation with &lt;n&gt; as start
                             number instead '1'
    since spcifier:
      -3 .................. e.g: create a patch from last three commits
      &lt;commit hash&gt; ....... create patch with commits starting after &lt;commit hash&gt;

  git am &lt;patch&gt; ......... apply patch and create a commit for it

  git apply --stat &lt;PATCH&gt; ... see which files the patch would change
  git apply --check &lt;PATCH&gt; .. see if the patch can be applied cleanly
  git apply &lt;PATCH&gt; .......... apply the patch locally without creating a commit

  # eg: generate patches for each commit from initial commit on
  git format-patch -N $(git rev-list --max-parents=0 HEAD)

  # generate single patch file from a certain commit/ref
  git format-patch &lt;COMMIT/REF&gt; --stdout &gt; my-patch.patch
</code></pre>
<h2 id="resetting"><a class="header" href="#resetting">Resetting</a></h2>
<pre><code class="language-markdown">  git reset [opt] &lt;ref|commit&gt;
    opt:
      --mixed .................... resets index, but not working tree
      --hard ..................... matches the working tree and index to that
                                   of the tree being switched to any changes to
                                   tracked files in the working tree since
                                   &lt;commit&gt; are lost
  git reset HEAD &lt;file&gt; .......... remove file from staging
  git reset --soft HEAD~1 ........ delete most recent commit but keep work
  git reset --hard HEAD~1 ........ delete most recent commit and delete work
</code></pre>
<h2 id="submodules"><a class="header" href="#submodules">Submodules</a></h2>
<pre><code class="language-markdown">  git submodule add &lt;url&gt; [&lt;path&gt;] .......... add new submodule to current project
  git clone --recursive &lt;url&gt; ............... clone project and recursively all
                                              submodules (same as using
                                              'git submodule update --init
                                              --recursive' after clone)
  git submodule update --init --recursive ... checkout submodules recursively
                                              using the commit listed in the
                                              super-project (in detached HEAD)
  git submodule update --remote &lt;submod&gt; .... fetch &amp; merge remote changes for
                                              &lt;submod&gt;, this will pull
                                              origin/HEAD or a branch specified
                                              for the submodule
  git diff --submodule ...................... show commits that are part of the
                                              submodule diff
</code></pre>
<h2 id="inspection"><a class="header" href="#inspection">Inspection</a></h2>
<pre><code class="language-markdown">  git ls-tree [-r] &lt;ref&gt; .... show git tree for &lt;ref&gt;, -r to recursively ls sub-trees
  git show &lt;obj&gt; ............ show &lt;obj&gt;
  git cat-file -p &lt;obj&gt; ..... print content of &lt;obj&gt;
</code></pre>
<h2 id="revision-specifier"><a class="header" href="#revision-specifier">Revision Specifier</a></h2>
<pre><code class="language-markdown">  HEAD ........ last commit
  HEAD~1 ...... last commit-1
  HEAD~N ...... last commit-N (linear backwards when in tree structure, check
                difference between HEAD^ and HEAD~)
  git rev-list --max-parents=0 HEAD ........... first commit
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="awk1"><a class="header" href="#awk1">awk(1)</a></h1>
<pre><code class="language-markdown">awk [opt] program [input]
    -F &lt;sepstr&gt;        field separator string (can be regex)
    program            awk program
    input              file or stdin if not file given
</code></pre>
<h2 id="input-processing"><a class="header" href="#input-processing">Input processing</a></h2>
<p>Input is processed in two stages:</p>
<ol>
<li>Splitting input into a sequence of <code>records</code>.
By default split at <code>newline</code> character, but can be changed via the
builtin <code>RS</code> variable.</li>
<li>Splitting a <code>record</code> into <code>fields</code>. By default strings without <code>whitespace</code>,
but can be changed via the builtin variable <code>FS</code> or command line option
<code>-F</code>.</li>
</ol>
<p>Fields are accessed as follows:</p>
<ul>
<li><code>$0</code> whole <code>record</code></li>
<li><code>$1</code> field one</li>
<li><code>$2</code> field two</li>
<li>...</li>
</ul>
<h2 id="program"><a class="header" href="#program">Program</a></h2>
<p>An <code>awk</code> program is composed of pairs of the form:</p>
<pre><code class="language-markdown">pattern { action }
</code></pre>
<p>The program is run against each <code>record</code> in the input stream. If a <code>pattern</code>
matches a <code>record</code> the corresponding <code>action</code> is executed and can access the
<code>fields</code>.</p>
<pre><code class="language-markdown">INPUT
  |
  v
record ----&gt; ∀ pattern matched
  |                   |
  v                   v
fields ----&gt; run associated action
</code></pre>
<p>Any valid awk <code>expr</code> can be a <code>pattern</code>.</p>
<h3 id="special-pattern"><a class="header" href="#special-pattern">Special pattern</a></h3>
<p>awk provides two special patterns, <code>BEGIN</code> and <code>END</code>, which can be used
multiple times. Actions with those patterns are <strong>executed exactly once</strong>.</p>
<ul>
<li><code>BEGIN</code> actions are run before processing the first record</li>
<li><code>END</code> actions are run after processing the last record</li>
</ul>
<h3 id="special-variables"><a class="header" href="#special-variables">Special variables</a></h3>
<ul>
<li><code>RS</code> <em>record separator</em>: first char is the record separator, by default
<newline></li>
<li><code>FS</code> <em>field separator</em>: regex to split records into fields, by default
<space></li>
<li><code>NR</code> <em>number record</em>: number of current record</li>
<li><code>NF</code> <em>number fields</em>: number of fields in the current record</li>
</ul>
<h3 id="special-statements--functions"><a class="header" href="#special-statements--functions">Special statements &amp; functions</a></h3>
<ul>
<li>
<p><code>printf &quot;fmt&quot;, args...</code></p>
<p>Print format string, args are comma separated.</p>
<ul>
<li><code>%s</code> string</li>
<li><code>%d</code> decimal</li>
<li><code>%x</code> hex</li>
<li><code>%f</code> float</li>
</ul>
<p>Width can be specified as <code>%Ns</code>, this reserves <code>N</code> chars for a string.
For floats one can use <code>%N.Mf</code>, <code>N</code> is the total number including <code>.</code> and
<code>M</code>.</p>
</li>
<li>
<p><code>sprintf(&quot;fmt&quot;, expr, ...)</code></p>
<p>Format the expressions according to the format string. Similar as <code>printf</code>,
but this is a function and return value can be assigned to a variable.</p>
</li>
<li>
<p><code>strftime(&quot;fmt&quot;)</code></p>
<p>Print time stamp formatted by <code>fmt</code>.</p>
<ul>
<li><code>%Y</code> full year (eg 2020)</li>
<li><code>%m</code> month (01-12)</li>
<li><code>%d</code> day (01-31)</li>
<li><code>%F</code> alias for <code>%Y-%m-%d</code></li>
<li><code>%H</code> hour (00-23)</li>
<li><code>%M</code> minute (00-59)</li>
<li><code>%S</code> second (00-59)</li>
<li><code>%T</code> alias for <code>%H:%M:%S</code></li>
</ul>
</li>
</ul>
<h2 id="examples"><a class="header" href="#examples">Examples</a></h2>
<h3 id="filter-records"><a class="header" href="#filter-records">Filter records</a></h3>
<pre><code class="language-bash">awk 'NR%2 == 0 { print $0 }' &lt;file&gt;
</code></pre>
<p>The pattern <code>NR%2 == 0</code> matches every second record and the action <code>{ print $0 }</code>
prints the whole record.</p>
<h3 id="negative-patterns"><a class="header" href="#negative-patterns">Negative patterns</a></h3>
<pre><code class="language-bash">awk '!/^#/ { print $1 }' &lt;file&gt;
</code></pre>
<p>Matches records not starting with <code>#</code>.</p>
<h3 id="access-last-fields-in-records"><a class="header" href="#access-last-fields-in-records">Access last fields in records</a></h3>
<pre><code class="language-bash">echo 'a b c d e f' | awk '{ print $NF $(NF-1) }'
</code></pre>
<p>Access last fields with arithmetic on the <code>NF</code> number of fields variable.</p>
<h3 id="capture-in-variables"><a class="header" href="#capture-in-variables">Capture in variables</a></h3>
<pre><code class="language-bash"># /proc/&lt;pid&gt;/status
#   Name:    cat
#   ...
#   VmRSS:   516 kB
#   ...

for f in /proc/*/status; do
    cat $f | awk '
             /^VmRSS/ { rss = $2/1024 }
             /^Name/ { name = $2 }
             END { printf &quot;%16s %6d MB\n&quot;, name, rss }';
done | sort -k2 -n
</code></pre>
<p>We capture values from <code>VmRSS</code> and <code>Name</code> into variables and print them at the
<code>END</code> once processing all records is done.</p>
<h3 id="capture-in-array"><a class="header" href="#capture-in-array">Capture in array</a></h3>
<pre><code class="language-bash">echo 'a 10
b 2
b 4
a 1' | awk '{
    vals[$1] += $2
    cnts[$1] += 1
}
END {
    for (v in vals)
        printf &quot;%s %d\n&quot;, v, vals[v] / cnts [v]
}'
</code></pre>
<p>Capture keys and values from different columns and some up the values.
At the <code>END</code> we compute the average of each key.</p>
<h3 id="run-shell-command-and-capture-output"><a class="header" href="#run-shell-command-and-capture-output">Run shell command and capture output</a></h3>
<pre><code class="language-bash">cat /proc/1/status | awk '
                     /^Pid/ {
                        &quot;ps --no-header -o user &quot; $2 | getline user;
                         print user
                     }'
</code></pre>
<p>We build a <code>ps</code> command line and capture the first line of the processes output
in the <code>user</code> variable and then print it.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="emacs1"><a class="header" href="#emacs1">emacs(1)</a></h1>
<h2 id="help"><a class="header" href="#help">help</a></h2>
<pre><code class="language-markdown">  C-h ?         list available help modes
  C-h e         show message output (`*Messages*` buffer)
  C-h f         describe function
  C-h v         describe variable
  C-h w         describe which key invoke function (where-is)
  C-h c &lt;KEY&gt;   print command bound to &lt;KEY&gt;
  C-h k &lt;KEY&gt;   describe command bound to &lt;KEY&gt;
  C-h b         list buffer local key-bindings
  &lt;kseq&gt; C-h    list possible key-bindings with &lt;kseq&gt;
                eg C-x C-h -&gt; list key-bindings beginning with C-x
</code></pre>
<h2 id="package-manager"><a class="header" href="#package-manager">package manager</a></h2>
<pre><code class="language-markdown">  key    fn                          description
------------------------------------------------
         package-refresh-contents    refresh package list
         package-list-packages       list available/installed packages
                                     `U x` to mark packages for Upgrade &amp; eXecute
</code></pre>
<h2 id="window"><a class="header" href="#window">window</a></h2>
<pre><code class="language-markdown">  key      fn                      description
----------------------------------------------
  C-x 0    delete-window           kill focused window
  C-x 1    delete-other-windows    kill all other windows
  C-x 2    split-window-below      split horizontal
  C-x 3    split-window-right      split vertical
  C-x o    other-window            other window (cycle)
</code></pre>
<h2 id="buffer"><a class="header" href="#buffer">buffer</a></h2>
<pre><code class="language-markdown">  key        fn                   description
---------------------------------------------
  C-x C-q    read-only-mode       toggle read-only mode for buffer
  C-x k      kill-buffer          kill buffer
  C-x s      save-some-buffers    save buffer
  C-x w      write-file           write buffer (save as)
  C-x b      switch-to-buffer     switch buffer
  C-x C-b    list-buffers         buffer list
</code></pre>
<h2 id="ibuffer"><a class="header" href="#ibuffer">ibuffer</a></h2>
<p>Builtin advanced buffer selection mode</p>
<pre><code class="language-markdown">  key        fn            description
--------------------------------------
             ibuffer       enter buffer selection

  h                        ibuffer help

  o                        open buffer in other window
  C-o                      open buffer in other window keep focus in ibuffer

  s a                      sort by buffer name
  s f                      sort by file name
  s v                      sort by last viewed
  s v                      sort by major mode
  ,                        cycle sorting mode

  =                        compare buffer against file on disk (if file is dirty `*`)

  /m                       filter by major mode
  /n                       filter by buffer name
  /f                       filter by file name
  //                       remove all filter

  /g                       create filter group
  /\                       remove all filter groups
</code></pre>
<h2 id="isearch"><a class="header" href="#isearch">isearch</a></h2>
<pre><code class="language-markdown">  key    fn                           description
-------------------------------------------------
  C-s    isearch-forward              search forward from current position (C-s to go to next match)
  C-r    isearch-backward             search backwards from current position (C-r to go to next match)
  C-w    isearch-yank-word-or-char    feed next word to current search (extend)
  M-p    isearch-ring-advance         previous search input
  M-n    isearch-ring-retreat         next search input
</code></pre>
<h2 id="occur"><a class="header" href="#occur">occur</a></h2>
<pre><code class="language-markdown">  key      fn           description
-----------------------------------
  M-s o    occur        get matches for regexp in buffer
                        use during `isearch` to use current search term

  C-n                   goto next line
  C-p                   goto previous line
  o                     open match in other window
  C-o                   open match in other window keep focus in ibuffer
</code></pre>
<pre><code class="language-markdown">  key      fn                                 description
---------------------------------------------------------
           multi-occur-in-matching-buffers    run occur in buffers matching regexp
</code></pre>
<h2 id="grep"><a class="header" href="#grep">grep</a></h2>
<pre><code class="language-markdown">  key    fn           description
-----------------------------------
         rgrep        recursive grep
         find-grep    run find-grep result in *grep* buffer

  n/p                 navigate next/previous match in *grep* buffer
  q                   quit *grep* buffer
</code></pre>
<h2 id="yankpaste"><a class="header" href="#yankpaste">yank/paste</a></h2>
<pre><code class="language-markdown">  key         fn                  description
---------------------------------------------
  C-&lt;SPACE&gt;   set-mark-command    set start mark to select text
  M-w         kill-ring-save      copy selected text
  C-w         kill-region         kill selected text
  C-y         yank                paste selected text
  M-y         yank-pop            cycle through kill-ring (only after paste)
</code></pre>
<h2 id="register"><a class="header" href="#register">register</a></h2>
<pre><code class="language-markdown">  key             fn                 description
------------------------------------------------
  C-x r s &lt;reg&gt;   copy-to-register   save region in register &lt;reg&gt;
  C-x r i &lt;reg&gt;   insert-register    insert content of register &lt;reg&gt;
</code></pre>
<h2 id="blockrect"><a class="header" href="#blockrect">block/rect</a></h2>
<pre><code class="language-markdown">  key          fn                    description
------------------------------------------------
  C-x &lt;SPC&gt;    rectangle-mark-mode   activate rectangle-mark-mode
               string-rectangle      insert text in marked rect
</code></pre>
<h2 id="mass-edit"><a class="header" href="#mass-edit">mass edit</a></h2>
<pre><code class="language-markdown">  key       fn                       description
------------------------------------------------
  C-x h     mark-whole-buffer        mark whole buffer
            delete-matching-line     delete lines matching regex
  M-%       query-replace            search &amp; replace
  C-M-%     query-replace-regexp     search &amp; replace regex
</code></pre>
<h2 id="narrow"><a class="header" href="#narrow">narrow</a></h2>
<pre><code class="language-markdown">  key       fn                    description
---------------------------------------------
  C-x n n   narrow-to-region      show only focused region (narrow)
  C-x n w   widen                 show whole buffer (wide)
</code></pre>
<h2 id="org"><a class="header" href="#org">org</a></h2>
<pre><code class="language-markdown">  key              fn   description
------------------------------------
  M-up/M-down           re-arrange items in same hierarchy
  M-left/M-right        change item hierarchy
  C-RET                 create new item below current
  C-S-RET               create new TODO item below current
  S-left/S-right        cycle TODO states
</code></pre>
<h3 id="org-source"><a class="header" href="#org-source">org source</a></h3>
<pre><code class="language-markdown">  key       fn     description
------------------------------
  &lt;s TAB           generate a source block
  C-c '            edit source block (in lang specific buffer)
  C-c C-c          eval source block
</code></pre>
<h2 id="comapny"><a class="header" href="#comapny">comapny</a></h2>
<pre><code class="language-markdown">  key         fn   description
-------------------------------
  C-s              search through completion candidates
  C-o              filter completion candidates based on search term
  &lt;f1&gt;             get doc for completion condidate
  M-&lt;digit&gt;        select completion candidate
</code></pre>
<h2 id="tags-1"><a class="header" href="#tags-1">tags</a></h2>
<p>To generate <code>etags</code> using <code>ctags</code></p>
<pre><code class="language-markdown">  ctags -R -e .         generate emacs tag file (important `-e`)
</code></pre>
<p>Navigate using tags</p>
<pre><code class="language-markdown">  key      fn                       description
-----------------------------------------------
           xref-find-definitions    find definition of tag
           xref-find-apropos        find symbols matching regexp
           xref-find-references     find references of tag
</code></pre>
<h2 id="lisp"><a class="header" href="#lisp">lisp</a></h2>
<pre><code class="language-markdown">  key   fn        description
------------------------------
        ielm      open interactive elips shell
</code></pre>
<p>In <code>lisp-interaction-mode</code> (<code>*scratch*</code> buffer by defult)</p>
<pre><code class="language-markdown">  key              fn                        description
--------------------------------------------------------
  C-j              eval-print-last-sexp      evaluate &amp; print preceeding lisp expr

  C-x C-e          eval-last-sexp            evaluate lisp expr
  C-u C-x C-e      eval-last-sexp            evaluate &amp; print
</code></pre>
<h2 id="ido"><a class="header" href="#ido">ido</a></h2>
<p>Builtin fuzzy completion mode (eg buffer select, dired, ...).</p>
<pre><code class="language-markdown">  key              fn          description
------------------------------------------
                  ido-mode     toggle ido mode
  &lt;Left&gt;/&lt;Right&gt;               cycle through available competions
  &lt;RET&gt;                        select completion
</code></pre>
<h2 id="evil"><a class="header" href="#evil">evil</a></h2>
<pre><code class="language-markdown">  key    fn    description
--------------------------
  C-z          toggle emacs/evil mode
  C-^          toggle between previous and current buffer
  C-p          after paste cycle kill-ring back
  C-n          after paste cycle kill-ring forward
</code></pre>
<h2 id="dired"><a class="header" href="#dired">dired</a></h2>
<pre><code class="language-markdown">  key    fn    description
--------------------------
  i            open sub-dir in same buffer
  +            create new directory
  C            copy file/dir

  q            quit
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gpg1"><a class="header" href="#gpg1">gpg(1)</a></h1>
<pre><code>gpg
  -o|--output                 Specify output file
  -a|--armor                  Create ascii output
  -u|--local-user &lt;name&gt;      Specify key for signing
  -r|--recipient              Encrypt for user
</code></pre>
<h2 id="generate-new-keypair"><a class="header" href="#generate-new-keypair">Generate new keypair</a></h2>
<pre><code class="language-bash">gpg --full-generate-key
</code></pre>
<h2 id="list-keys"><a class="header" href="#list-keys">List keys</a></h2>
<pre><code>gpg -k / --list-key               # public keys
gpg -K / --list-secret-keys       # secret keys
</code></pre>
<h2 id="edit-keys"><a class="header" href="#edit-keys">Edit keys</a></h2>
<pre><code class="language-bash">gpg --edit-key &lt;KEY ID&gt;
</code></pre>
<p>Gives prompt to modify <code>KEY ID</code>, common commands:</p>
<pre><code class="language-bash">help         show help
save         save &amp; quit

list         list keys and user IDs
key &lt;N&gt;      select subkey &lt;N&gt;
uid &lt;N&gt;      select user ID &lt;N&gt;

expire       change expiration of selected key

adduid       add user ID
deluid       delete selected user ID

addkey       add subkey
delkey       delete selected subkey
</code></pre>
<h2 id="export--import-keys"><a class="header" href="#export--import-keys">Export &amp; Import Keys</a></h2>
<pre><code class="language-bash">gpg --export --armor --output &lt;KEY.PUB&gt; &lt;KEY ID&gt;
gpg --export-secret-key --armor --output &lt;KEY.PUB&gt; &lt;KEY ID&gt;
gpg --import &lt;FILE&gt;
</code></pre>
<h2 id="search--send-keys"><a class="header" href="#search--send-keys">Search &amp; Send keys</a></h2>
<pre><code class="language-bash">gpg --keyserver &lt;SERVER&gt; --send-keys &lt;KEY ID&gt;
gpg --keyserver &lt;SERVER&gt; --search-keys &lt;KEY ID&gt;
</code></pre>
<h2 id="encrypt-passphrase"><a class="header" href="#encrypt-passphrase">Encrypt (passphrase)</a></h2>
<p>Encrypt file using <code>passphrase</code> and write encrypted data to <code>&lt;file&gt;.gpg</code>.</p>
<pre><code class="language-bash">gpg --symmetric &lt;file&gt;

# Decrypt using passphrase
gpg -o &lt;file&gt; --decrypt &lt;file&gt;.gpg
</code></pre>
<h2 id="encrypt-public-key"><a class="header" href="#encrypt-public-key">Encrypt (public key)</a></h2>
<p>Encrypt file with <code>public key</code> of specified <code>recipient</code> and write encrypted
data to <code>&lt;file&gt;.gpg</code>.</p>
<pre><code class="language-bash">gpg --encrypt -r foo@bar.de &lt;file&gt;

# Decrypt at foos side (private key required)
gpg -o &lt;file&gt; --decrypt &lt;file&gt;.gpg
</code></pre>
<h2 id="signing"><a class="header" href="#signing">Signing</a></h2>
<p>Generate a signed file and write to <code>&lt;file&gt;.gpg</code>.</p>
<pre><code class="language-bash"># Sign with private key of foo@bar.de
gpg --sign -u foor@bar.de &lt;file&gt;

# Verify with public key of foo@bar.de
gpg --verify &lt;file&gt;

# Extract content from signed file
gpg -o &lt;file&gt; --decrypt &lt;file&gt;.gpg
</code></pre>
<blockquote>
<p>Without <code>-u</code> use first private key in list <code>gpg -K</code> for signing.</p>
</blockquote>
<p>Files can also be <code>signed</code> and <code>encrypted</code> at once, gpg will first sign the
file and then encrypt it.</p>
<pre><code class="language-bash">gpg --sign --encrypt -r &lt;recipient&gt; &lt;file&gt;
</code></pre>
<h2 id="signing-detached"><a class="header" href="#signing-detached">Signing (detached)</a></h2>
<p>Generate a <code>detached</code> signature and write to <code>&lt;file&gt;.asc</code>.
Send <code>&lt;file&gt;.asc</code> along with <code>&lt;file&gt;</code> when distributing.</p>
<pre><code class="language-bash">gpg --detach-sign --armor -u foor@bar.de &lt;file&gt;

# Verify
gpg --verify &lt;file&gt;.asc &lt;file&gt;
</code></pre>
<blockquote>
<p>Without <code>-u</code> use first private key in list <code>gpg -K</code> for signing.</p>
</blockquote>
<h2 id="abbreviations"><a class="header" href="#abbreviations">Abbreviations</a></h2>
<ul>
<li><code>sec</code> secret key</li>
<li><code>ssb</code> secret subkey</li>
<li><code>pub</code> public key</li>
<li><code>sub</code> public subkey</li>
</ul>
<h2 id="keyservers"><a class="header" href="#keyservers">Keyservers</a></h2>
<ul>
<li>http://pgp.mit.edu</li>
<li>http://keyserver.ubuntu.com</li>
<li>hkps://pgp.mailbox.org</li>
</ul>
<h2 id="examples-1"><a class="header" href="#examples-1">Examples</a></h2>
<h3 id="list-basic-key-information-from-file-with-long-keyids"><a class="header" href="#list-basic-key-information-from-file-with-long-keyids">List basic key information from file with long keyids</a></h3>
<pre><code class="language-bash">gpg --keyid-format 0xlong &lt;key.asc&gt;
</code></pre>
<h3 id="extend-expiring-key"><a class="header" href="#extend-expiring-key">Extend expiring key</a></h3>
<pre><code class="language-bash">gpg --edit-key &lt;key id&gt;

# By default we are on the primary key, can switch to sub key.
gpg&gt; key 1

# Update the expire date.
gpg&gt; expire

gpg&gt; save

# Update keyserver(s) and/or export new pub keyfile.
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gdb1"><a class="header" href="#gdb1">gdb(1)</a></h1>
<h1 id="cli"><a class="header" href="#cli">CLI</a></h1>
<pre><code class="language-markdown">  gdb [opts] [prg [-c coredump | -p pid]]
  gdb [opts] --args prg &lt;prg-args&gt;
    opts:
      -p &lt;pid&gt;        attach to pid
      -c &lt;coredump&gt;   use &lt;coredump&gt;
      -x &lt;file&gt;       execute script &lt;file&gt; before prompt
      -ex &lt;cmd&gt;       execute command &lt;cmd&gt; before prompt
      --tty &lt;tty&gt;     set I/O tty for debugee
</code></pre>
<h1 id="interactive-usage"><a class="header" href="#interactive-usage">Interactive usage</a></h1>
<h2 id="misc"><a class="header" href="#misc">Misc</a></h2>
<pre><code class="language-markdown">  tty &lt;tty&gt;
          Set &lt;tty&gt; as tty for debugee.
          Make sure nobody reads from target tty, easiest is to spawn a shell
          and run following in target tty:
          &gt; while true; do sleep 1024; done

  sharedlibrary [&lt;regex&gt;]
          Load symbols of shared libs loaded by debugee. Optionally use &lt;regex&gt;
          to filter libs for symbol loading.

  display [/FMT] &lt;expr&gt;
          Print &lt;expr&gt; every time debugee stops. Eg print next instr, see
          examples below.

  undisplay [&lt;num&gt;]
          Delete display expressions either all or one referenced by &lt;num&gt;.

  info display
          List display expressions.
</code></pre>
<h2 id="breakpoints"><a class="header" href="#breakpoints">Breakpoints</a></h2>
<pre><code class="language-markdown">  break [-qualified] &lt;sym&gt; thread &lt;tnum&gt;
          Set a breakpoint only for a specific thread.
          -qualified: Treat &lt;sym&gt; as fully qualified symbol (quiet handy to set
          breakpoints on C symbols in C++ contexts)

  break &lt;sym&gt; if &lt;cond&gt;
          Set conditional breakpoint (see examples below).

  delete [&lt;num&gt;]
          Delete breakpoint either all or one referenced by &lt;num&gt;.

  info break
          List breakpoints.

  cond &lt;bp&gt; &lt;cond&gt;
          Make existing breakpoint &lt;bp&gt; conditional with &lt;cond&gt;.

  tbreak
          Set temporary breakpoint, will be deleted when hit.
          Same syntax as `break`.

  rbreak &lt;regex&gt;
          Set breakpoints matching &lt;regex&gt;, where matching internally is done
          on: .*&lt;regex&gt;.*

  command [&lt;bp_list&gt;]
          Define commands to run after breakpoint hit. If &lt;bp_list&gt; is not
          specified attach command to last created breakpoint. Command block
          terminated with 'end' token.

          &lt;bp_list&gt;: Space separates list, eg 'command 2 5-8' to run command
          for breakpoints: 2,5,6,7,8.

  save break &lt;file&gt;
          Save breakpoints to &lt;file&gt;. Can be loaded with the `source` command.
</code></pre>
<h2 id="watchpoints"><a class="header" href="#watchpoints">Watchpoints</a></h2>
<pre><code class="language-markdown">  watch [-location|-l] &lt;expr&gt; [thread &lt;tnum&gt;]
          Create a watchpoint for &lt;expr&gt;, will break if &lt;expr&gt; is written to.
          Watchpoints respect scope of variables, -l can be used to watch the
          memory location instead.
  rwatch ...
          Sets a read watchpoint, will break if &lt;expr&gt; is read from.
  awatch ...
          Sets an access watchpoint, will break if &lt;expr&gt; is written to or read
          from.
</code></pre>
<h2 id="inspection-1"><a class="header" href="#inspection-1">Inspection</a></h2>
<pre><code class="language-markdown">  info functions [&lt;regex&gt;]
          List functions matching &lt;regex&gt;. List all functions if no &lt;regex&gt;
          provided.

  info variables [&lt;regex&gt;]
          List variables matching &lt;regex&gt;. List all variables if no &lt;regex&gt;
          provided.
</code></pre>
<h2 id="signal-handling"><a class="header" href="#signal-handling">Signal handling</a></h2>
<pre><code class="language-markdown">  info handle [&lt;signal&gt;]
          Print how to handle &lt;signal&gt;. If no &lt;signal&gt; specified print for all
          signals.

  handle &lt;signal&gt; &lt;action&gt;
          Configure how gdb handles &lt;signal&gt; sent to debugee.
          &lt;action&gt;:
            stop/nostop       Catch signal in gdb and break.
            print/noprint     Print message when gdb catches signal.
            pass/nopass       Pass signal down to debugee.

  catch signal &lt;signal&gt;
          Create a catchpoint for &lt;signal&gt;.
</code></pre>
<h2 id="source-file-locations"><a class="header" href="#source-file-locations">Source file locations</a></h2>
<pre><code class="language-markdown">  dir &lt;path&gt;
          Add &lt;path&gt; to the beginning of the searh path for source files.

  show dir
          Show current search path.

  set substitute-path &lt;from&gt; &lt;to&gt;
          Add substitution rule checked during source file lookup.

  show substitute-path
          Show current substitution rules.
</code></pre>
<h2 id="configuration"><a class="header" href="#configuration">Configuration</a></h2>
<pre><code class="language-markdown">  set disassembly-flavor &lt;intel | att&gt;
          Set the disassembly style &quot;flavor&quot;.

  set follow-fork-mode &lt;child | parent&gt;
          Specify which process to follow when debuggee makes a fork(2)
          syscall.

  set pagination &lt;on | off&gt;
          Turn on/off gdb's pagination.

  set breakpoint pending &lt;on | off | auto&gt;
          on: always set pending breakpoints.
          off: error when trying to set pending breakpoints.
          auto: interatively query user to set breakpoint.

  set print pretty &lt;on | off&gt;
          Turn on/off pertty printing of structures.

  set logging &lt;on | off&gt;
          Enable output logging to file (default gdb.txt).

  set logging file &lt;fname&gt;
          Change output log file to &lt;fname&gt;

  set logging redirect &lt;on/off&gt;
          on: only log to file.
          off: log to file and tty.
</code></pre>
<h1 id="user-commands-macros"><a class="header" href="#user-commands-macros">User commands (macros)</a></h1>
<p>Gdb allows to create &amp; document user commands as follows:</p>
<pre><code class="language-markdown">  define &lt;cmd&gt;
    # cmds
  end

  document &lt;cmd&gt;
    # docu
  end
</code></pre>
<p>To get all user commands or documentations one can use:</p>
<pre><code class="language-markdown">  help user-defined
  help &lt;cmd&gt;
</code></pre>
<h1 id="hooks"><a class="header" href="#hooks">Hooks</a></h1>
<p>Gdb allows to create two types of command <code>hooks</code></p>
<ul>
<li><code>hook-</code> will be run before <code>&lt;cmd&gt;</code></li>
<li><code>hookpost-</code> will be run after <code>&lt;cmd&gt;</code></li>
</ul>
<pre><code class="language-markdown">  define hook-&lt;cmd&gt;
    # cmds
  end

  define hookpost-&lt;cmd&gt;
    # cmds
  end
</code></pre>
<h1 id="examples-2"><a class="header" href="#examples-2">Examples</a></h1>
<h2 id="automatically-print-next-instr"><a class="header" href="#automatically-print-next-instr">Automatically print next instr</a></h2>
<p>When ever the debugee stops automatically print the memory at the current
instruction pointer (<code>$rip</code> x86) and format as instruction <code>/i</code>.</p>
<pre><code class="language-markdown">  # rip - x86
  display /i $rip

  # step instruction, after the step the next instruction is automatically printed
  si
</code></pre>
<h2 id="conditional-breakpoints"><a class="header" href="#conditional-breakpoints">Conditional breakpoints</a></h2>
<p>Create conditional breakpoints for a function <code>void foo(int i)</code> in the debugee.</p>
<pre><code class="language-markdown">  # Create conditional breakpoint
  b foo if i == 42

  b foo     # would create bp 2
  # Make existing breakpoint conditional
  cond 2 if i == 7
</code></pre>
<h2 id="catch-sigsegv-and-execute-commands"><a class="header" href="#catch-sigsegv-and-execute-commands">Catch SIGSEGV and execute commands</a></h2>
<p>This creates a <code>catchpoint</code> for the <code>SIGSEGV</code> signal and attached the <code>command</code>
to it.</p>
<pre><code class="language-markdown">  catch signal SIGSEGV
  command
    bt
    c
  end
</code></pre>
<h2 id="run-backtrace-on-thread-1-batch-mode"><a class="header" href="#run-backtrace-on-thread-1-batch-mode">Run <code>backtrace</code> on thread 1 (batch mode)</a></h2>
<pre><code class="language-markdown">  gdb --batch -ex 'thread 1' -ex 'bt' -p &lt;pid&gt;
</code></pre>
<h2 id="script-gdb-for-automating-debugging-sessions"><a class="header" href="#script-gdb-for-automating-debugging-sessions">Script gdb for automating debugging sessions</a></h2>
<p>To script gdb add commands into a file and pass it to gdb via <code>-x</code>.
For example create <code>run.gdb</code>:</p>
<pre><code class="language-markdown">  set pagination off

  break mmap
  command
    info reg rdi rsi rdx
    bt
    c
  end

  #initial drop
  c
</code></pre>
<p>This script can be used as:</p>
<pre><code class="language-markdown">  gdb --batch -x ./run.gdb -p &lt;pid&gt;
</code></pre>
<h2 id="hook-to-automatically-save-breakpoints-on-quit"><a class="header" href="#hook-to-automatically-save-breakpoints-on-quit">Hook to automatically save breakpoints on <code>quit</code></a></h2>
<pre><code class="language-markdown">define break-save
    save breakpoint $arg0.gdb.bp
end
define break-load
    source $arg0.gdb.bp
end

define hook-quit
    break-save quit
end
</code></pre>
<h2 id="watchpoint-on-struct--class-member"><a class="header" href="#watchpoint-on-struct--class-member">Watchpoint on struct / class member</a></h2>
<p>A symbolic watchpoint defined on a member variable for debugging is only valid
as long as the expression is in scope. Once out of scope the watchpoint gets
deleted.</p>
<p>When debugging some memory corruption we want to keep the watchpoint even the
expression goes out of scope to find the location that overrides the variable
and introduces the corruption.</p>
<pre><code class="language-markdown">(gdb) l
1  struct S { int v; };
2
3  void set(struct S* s, int v) {
4      s-&gt;v = v;
5  }
6
7  int main() {
8      struct S s;
9      set(&amp;s, 1);
10     set(&amp;s, 2);
11     set(&amp;s, 3);
...

(gdb) s
set (s=0x7fffffffe594, v=1) at test.c:4
4    s-&gt;v = v;

# Define a new watchpoint on the member of the struct. The expression however
# is only valid in the current functions scope.

(gdb) watch s-&gt;v
Hardware watchpoint 2: s-&gt;v

(gdb) c
Hardware watchpoint 2: s-&gt;v
Old value = 0
New value = 1
set (s=0x7fffffffe594, v=1) at test.c:5
5   }

# The watchpoint gets deleted as soon as we leave the function scope.

(gdb) c
Watchpoint 2 deleted because the program has left the block in
which its expression is valid.
main () at test.c:10
10      set(&amp;s, 2);

(gdb) p &amp;s-&gt;v
$1 = (int *) 0x7fffffffe594

# Define a watchpoint o the address of the member variable of the s instance.
# This of course only makes sense as long as the s instance is not moved in memory.

(gdb) watch *0x7fffffffe594
Hardware watchpoint 3: *0x7fffffffe594

(gdb) c
Hardware watchpoint 3: *0x7fffffffe594
Old value = 1
New value = 2
set (s=0x7fffffffe594, v=2) at test.c:5
5   }

(gdb) c
Hardware watchpoint 3: *0x7fffffffe594
Old value = 2
New value = 3
set (s=0x7fffffffe594, v=3) at test.c:5
5   }
</code></pre>
<h1 id="know-bugs"><a class="header" href="#know-bugs">Know Bugs</a></h1>
<h2 id="workaround-command--finish-bug"><a class="header" href="#workaround-command--finish-bug">Workaround <code>command + finish</code> bug</a></h2>
<p>When using <code>finish</code> inside a <code>command</code> block, commands after <code>finish</code> are not
executed. To workaround that bug one can create a wrapper function which calls
<code>finish</code>.</p>
<pre><code class="language-markdown">  define handler
    bt
    finish
    info reg rax
  end

  command
    handler
  end
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gdbserver1"><a class="header" href="#gdbserver1">gdbserver(1)</a></h1>
<h1 id="cli-1"><a class="header" href="#cli-1">CLI</a></h1>
<pre><code class="language-markdown">  gdbserver [opts] comm prog [args]
    opts:
      --disable-randomization
      --no-disable-randomization

    comm:
      host:port
      tty
</code></pre>
<h1 id="example-4"><a class="header" href="#example-4">Example</a></h1>
<pre><code class="language-markdown"># Start gdbserver.
gdbserver localhost:1234 /bin/ls

# Attach gdb.
gdb -ex 'target remote localhost:1234'
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="radare21"><a class="header" href="#radare21">radare2(1)</a></h1>
<h2 id="print"><a class="header" href="#print">print</a></h2>
<pre><code class="language-markdown">
  pd &lt;n&gt; [@ &lt;addr&gt;]     # print disassembly for &lt;n&gt; instructions
                        # with optional temporary seek to &lt;addr&gt;
</code></pre>
<h2 id="flags"><a class="header" href="#flags">flags</a></h2>
<pre><code class="language-markdown">  fs            # list flag-spaces
  fs &lt;fs&gt;       # select flag-space &lt;fs&gt;
  f             # print flags of selected flag-space
</code></pre>
<h2 id="help-1"><a class="header" href="#help-1">help</a></h2>
<pre><code class="language-markdown">  ?*~&lt;kw&gt;       # '?*' list all commands and '~' grep for &lt;kw&gt;
  ?*~...        # '..' less mode /'...' interactive search
</code></pre>
<h2 id="relocation"><a class="header" href="#relocation">relocation</a></h2>
<pre><code class="language-markdown">  &gt; r2 -B &lt;baddr&gt; &lt;exe&gt;         # open &lt;exe&gt; mapped to addr &lt;baddr&gt;
  oob &lt;addr&gt;                    # reopen current file at &lt;baddr&gt;
</code></pre>
<h1 id="examples-3"><a class="header" href="#examples-3">Examples</a></h1>
<h2 id="patch-file-alter-bytes"><a class="header" href="#patch-file-alter-bytes">Patch file (alter bytes)</a></h2>
<pre><code class="language-markdown">  &gt; r2 [-w] &lt;file&gt;
  oo+           # re-open for write if -w was not passed
  s &lt;addr&gt;      # seek to position
  wv &lt;data&gt;     # write 4 byte (dword)
</code></pre>
<h2 id="assemble--disassmble-rasm2"><a class="header" href="#assemble--disassmble-rasm2">Assemble / Disassmble (rasm2)</a></h2>
<pre><code class="language-markdown">  rasm2 -L      # list supported archs

  &gt; rasm2 -a x86 'mov eax, 0xdeadbeef'
  b8efbeadde

  &gt; rasm2 -a x86 -d &quot;b8efbeadde&quot;
  mov eax, 0xdeadbeef
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="qemu1"><a class="header" href="#qemu1">qemu(1)</a></h1>
<p>All the examples &amp; notes use <code>qemu-system-x86_64</code> but in most cases
this can be swapped with the system emulator for other architectures.</p>
<h2 id="keybindings-1"><a class="header" href="#keybindings-1">Keybindings</a></h2>
<p>Graphic mode:</p>
<pre><code class="language-markdown">Ctrl+Alt+g         release mouse capture from VM

Ctrl+Alt+1         switch to display of VM
Ctrl+Alt+2         switch to qemu monitor
</code></pre>
<p>No graphic mode:</p>
<pre><code class="language-markdown">Ctrl+a h           print help
Ctrl+a x           exit emulator
Ctrl+a c           switch between monitor and console
</code></pre>
<h2 id="vm-config-snippet"><a class="header" href="#vm-config-snippet">VM config snippet</a></h2>
<p>Following command-line gives a good starting point to assemble a VM:</p>
<pre><code>qemu-system-x86_64                 \
    -cpu host -enable-kvm -smp 4   \
    -m 8G                          \
    -vga virtio -display sdl,gl=on \
    -boot menu=on                  \
    -cdrom &lt;iso&gt;                   \
    -hda &lt;disk&gt;                    \
    -device qemu-xhci,id=xhci      \
    -device usb-host,bus=xhci.0,vendorid=0x05e1,productid=0x0408,id=capture-card
</code></pre>
<h3 id="cpu--ram"><a class="header" href="#cpu--ram">CPU &amp; RAM</a></h3>
<pre><code class="language-bash"># Emulate host CPU in guest VM, enabling all supported host featured (requires KVM).
# List available CPUs `qemu-system-x86_64 -cpu help`.
-cpu host

# Enable KVM instead software emulation.
-enable-kvm

# Configure number of guest CPUs.
-smp &lt;N&gt;

# Configure size of guest RAM.
-m 8G
</code></pre>
<h3 id="graphic--display"><a class="header" href="#graphic--display">Graphic &amp; Display</a></h3>
<pre><code class="language-bash"># Use sdl window as display and enable openGL context.
-display sdl,gl=on

# Use vnc server as display (eg on display `:42` here).
-display vnc=localhost:42

# Confifure virtio as 3D video graphic accelerator (requires virgl in guest).
-vga virtio
</code></pre>
<h3 id="boot-menu"><a class="header" href="#boot-menu">Boot Menu</a></h3>
<pre><code class="language-bash"># Enables boot menu to select boot device (enter with `ESC`).
-boot menu=on
</code></pre>
<h3 id="block-devices"><a class="header" href="#block-devices">Block devices</a></h3>
<pre><code class="language-bash"># Attach cdrom drive with iso to a VM.
-cdrom &lt;iso&gt;

# Attach disk drive to a VM.
-hda &lt;disk&gt;

# Generic way to configure &amp; attach a drive to a VM.
-drive file=&lt;file&gt;,format=qcow2
</code></pre>
<h4 id="create-a-disk-with-qemu-img"><a class="header" href="#create-a-disk-with-qemu-img">Create a disk with <a href="https://qemu-project.gitlab.io/qemu/tools/qemu-img.html"><code>qemu-img</code></a></a></h4>
<p>To create a <code>qcow2</code> disk (qemu copy-on-write) of size <code>10G</code>:</p>
<pre><code class="language-bash">qemu-img create -f qcow2 disk.qcow2 10G
</code></pre>
<p>The disk does not contain any <code>partitions</code> or a <code>partition table</code>.
We can format the disk from <strong>within the <strong>guest</strong></strong> as following example:</p>
<pre><code class="language-bash"># Create `gpt` partition table.
sudo parted /dev/sda mktable gpt

# Create two equally sized primary partitions.
sudo parted /dev/sda mkpart primary 0% 50%
sudo parted /dev/sda mkpart primary 50% 100%

# Create filesystem on each partition.
sudo mkfs.ext3 /dev/sda1
sudo mkfs.ext4 /dev/sda2

lsblk -f /dev/sda
  NAME   FSTYPE LABEL UUID FSAVAIL FSUSE% MOUNTPOINT
  sda
  ├─sda1 ext3         ....
  └─sda2 ext4         ....
</code></pre>
<h3 id="usb"><a class="header" href="#usb">USB</a></h3>
<h4 id="host-controller"><a class="header" href="#host-controller">Host Controller</a></h4>
<pre><code class="language-bash"># Add XHCI USB controller to the VM (supports USB 3.0, 2.0, 1.1).
# `id=xhci` creates a usb bus named `xhci`.
-device qemu-xhci,id=xhci
</code></pre>
<h4 id="usb-device"><a class="header" href="#usb-device">USB Device</a></h4>
<pre><code class="language-bash"># Pass-through USB device from host identified by vendorid &amp; productid and
# attach to usb bus `xhci.0` (defined with controller `id`).
-device usb-host,bus=xhci.0,vendorid=0x05e1,productid=0x0408
</code></pre>
<h2 id="debugging"><a class="header" href="#debugging">Debugging</a></h2>
<pre><code class="language-bash"># Open gdbstub on tcp `&lt;port&gt;` (`-s` shorthand for `-gdb tcp::1234`).
-gdb tcp::&lt;port&gt;

# Freeze guest CPU at startup and wait for debugger connection.
-S
</code></pre>
<h2 id="io-redirection-2"><a class="header" href="#io-redirection-2">IO redirection</a></h2>
<pre><code class="language-bash"># Create raw tcp server for `serial IO` and wait until a client connects
# before executing the guest.
-serial tcp:localhost:12345,server,wait

# Create telnet server for `serial IO` and wait until a client connects
# before executing the guest.
-serial telnet:localhost:12345,server,wait

# Configure redirection for the QEMU `mointor`, arguments similar to `-serial`
# above.
-monitor ...
</code></pre>
<blockquote>
<p>In <code>server</code> mode use <code>nowait</code> to execute guest without waiting for a client
connection.</p>
</blockquote>
<h2 id="network"><a class="header" href="#network">Network</a></h2>
<pre><code class="language-bash"># Redirect host tcp port `1234` to guest port `4321`.
-nic user,hostfwd=tcp:localhost:1234-:4321
</code></pre>
<h2 id="shared-drives"><a class="header" href="#shared-drives">Shared drives</a></h2>
<pre><code class="language-bash"># Attach a `virtio-9p-pci` device to the VM.
# The guest requires 9p support and can mount the shared drive as:
#   mount -t 9p -o trans=virtio someName /mnt
-virtfs local,id=someName,path=&lt;someHostPath&gt;,mount_tag=someName,security_model=none
</code></pre>
<h2 id="debug-logging"><a class="header" href="#debug-logging">Debug logging</a></h2>
<pre><code class="language-bash"># List debug items.
-d help

# Write debug log to file instead stderr.
-D &lt;file&gt;

# Examples
-d in_asm       Log executed guest instructions.
</code></pre>
<h2 id="tracing"><a class="header" href="#tracing">Tracing</a></h2>
<pre><code class="language-bash"># List name of all trace points.
-trace help

# Enable trace points matching pattern and optionally write trace to file.
-trace &lt;pattern&gt;[,file=&lt;file&gt;]

# Enable trace points for all events listed in the &lt;events&gt; file.
# File must contain one event/pattern per line.
-trace events=&lt;events&gt;
</code></pre>
<h2 id="vm-snapshots"><a class="header" href="#vm-snapshots">VM snapshots</a></h2>
<p>VM snapshots require that there is at least on <code>qcow2</code> disk attached to the VM
(<a href="https://qemu-project.gitlab.io/qemu/system/images.html#vm-005fsnapshots">VM Snapshots</a>).</p>
<p>Commands for qemu <a href="https://qemu-project.gitlab.io/qemu/system/monitor.html">Monitor</a> or <a href="https://qemu-project.gitlab.io/qemu/interop/qemu-qmp-ref.html">QMP</a>:</p>
<pre><code class="language-bash"># List available snapshots.
info snapshots

# Create/Load/Delete snapshot with name &lt;tag&gt;.
savevm &lt;tag&gt;
loadvm &lt;tag&gt;
delvm &lt;tag&gt;
</code></pre>
<p>The snapshot can also be directly specified when invoking qemu as:</p>
<pre><code class="language-bash">qemu-system-x86_64 \
    -loadvm &lt;tag&gt;  \
    ...
</code></pre>
<h2 id="vm-migration"><a class="header" href="#vm-migration">VM Migration</a></h2>
<p><code>Online</code> migration example:</p>
<pre><code class="language-bash"># Start machine 1 on host ABC.
qemu-system-x86_64 -monitor stdio -cdrom &lt;iso&gt;

# Prepare machine 2 on host DEF as migration target.
# Listen for any connection on port 12345.
qemu-system-x86_64 -monitor stdio -incoming tcp:0.0.0.0:12345

# Start migration from the machine 1 monitor console.
(qemu) migrate tcp:DEF:12345
</code></pre>
<p>Save to external file example:</p>
<pre><code class="language-bash">```bash
# Start machine 1.
qemu-system-x86_64 -monitor stdio -cdrom &lt;iso&gt;

# Save VM state to file.
(qemu) migrate &quot;exec:gzip -c &gt; vm.gz&quot;

# Load VM from file.
qemu-system-x86_64 -monitor stdio -incoming &quot;exec: gzip -d -c vm.gz&quot;
</code></pre>
<blockquote>
<p>The migration source machine and the migration target machine should be
launched with the <strong>same</strong> parameters.</p>
</blockquote>
<h2 id="appendix-direct-kernel-boot"><a class="header" href="#appendix-direct-kernel-boot">Appendix: Direct <code>Kernel</code> boot</a></h2>
<p>Example command line to directly boot a <code>Kernel</code> with an <code>initrd</code> ramdisk.</p>
<pre><code class="language-bash">qemu-system-x86_64                                                     \
    -cpu host                                                          \
    -enable-kvm                                                        \
    -kernel &lt;dir&gt;/arch/x86/boot/bzImage                                \
    -append &quot;earlyprintk=ttyS0 console=ttyS0 nokaslr init=/init debug&quot; \
    -initrd &lt;dir&gt;/initramfs.cpio.gz                                    \
    ...
</code></pre>
<p>Instructions to build a minimal <a href="https://blog.memzero.de/kernel-debugging-qemu"><code>Kernel</code> and <code>initrd</code></a>.</p>
<h2 id="appendix-cheap-instruction-tracer"><a class="header" href="#appendix-cheap-instruction-tracer">Appendix: Cheap instruction tracer</a></h2>
<pre><code class="language-make">test: test.s
	as -o test.o test.s
	ld -o test test.o testc.o

trace: test
	qemu-x86_64 -singlestep -d nochain,cpu ./test 2&gt;&amp;1 | awk '/RIP/ { print $$1; }'

clean:
	$(RM) test test-bin test.o
</code></pre>
<pre><code class="language-x86asm">.section .text, &quot;ax&quot;

.global _start
_start:
    xor %rax, %rax
    mov $0x8, %rax
1:
    cmp $0, %rax
    je 2f
    dec %rax
    jmp 1b
2:
    # x86-64 exit(2) syscall
    mov $0, %rdi
    mov $60, %rax
    syscall
</code></pre>
<h2 id="references"><a class="header" href="#references">References</a></h2>
<ul>
<li><a href="https://github.com/qemu/qemu/blob/master/docs/usb2.txt">QEMU USB</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/tools/qemu-img.html">QEMU IMG</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/tools/index.html">QEMU Tools</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/system/index.html">QEMU System</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/system/invocation.html">QEMU Invocation (command line args)</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/system/monitor.html">QEMU Monitor</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/interop/qemu-qmp-ref.html">QEMU machine protocol (QMP)</a></li>
<li><a href="https://qemu-project.gitlab.io/qemu/system/images.html#vm-005fsnapshots">QEMU VM Snapshots</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="pacman1"><a class="header" href="#pacman1">pacman(1)</a></h1>
<h2 id="remote-package-repositories"><a class="header" href="#remote-package-repositories">Remote package repositories</a></h2>
<pre><code class="language-text">pacman -Sy              refresh package database
pacman -S &lt;pkg&gt;         install pkg
pacman -Ss &lt;regex&gt;      search remote package database
pacman -Si &lt;pkg&gt;        get info for pkg
pacman -Su              upgrade installed packages
pacman -Sc              clean local package cache
</code></pre>
<h2 id="remove-packages"><a class="header" href="#remove-packages">Remove packages</a></h2>
<pre><code class="language-text">pacman -Rsn &lt;pkg&gt;               uninstall package and unneeded deps + config files
</code></pre>
<h2 id="local-package-database"><a class="header" href="#local-package-database">Local package database</a></h2>
<p>Local package database of installed packages.</p>
<pre><code class="language-text">pacman -Q               list all installed packages
pacman -Qs &lt;regex&gt;      search local package database
pacman -Ql &lt;pkg&gt;        list files installed by pkg
pacman -Qo &lt;file&gt;       query package that owns file
pacman -Qe              only list explicitly installed packages
</code></pre>
<h2 id="local-file-database"><a class="header" href="#local-file-database">Local file database</a></h2>
<p>Local file database which allows to search packages owning certain files.
Also searches non installed packages, but database must be synced.</p>
<pre><code class="language-text">pacman -Fy              refresh file database
pacman -Fl &lt;pkg&gt;        list files in pkg (must not be installed)
pacman -Fx &lt;regex&gt;      search 
</code></pre>
<h2 id="hacks"><a class="header" href="#hacks">Hacks</a></h2>
<p>Uninstall all orphaned packages (including config files) that were installed as
dependencies.</p>
<pre><code class="language-text">pacman -Rsn $(pacman -Qtdq)
</code></pre>
<p>List explicitly installed packages that are not required as dependency by any
package and sort by size.</p>
<pre><code class="language-text">pacman -Qetq | xargs pacman -Qi |
    awk '/Name/ { name=$3 }
         /Installed Size/ { printf &quot;%8.2f%s %s\n&quot;, $4, $5, name }' |
    sort -h
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="dot1"><a class="header" href="#dot1">dot(1)</a></h1>
<p><a href="https://edotor.net/">Online playground</a></p>
<h2 id="example-dot-file-to-copy--paste-from"><a class="header" href="#example-dot-file-to-copy--paste-from">Example <code>dot</code> file to copy &amp; paste from.</a></h2>
<p>Can be rendered to <code>svg</code> with the following command.</p>
<pre><code class="language-bash">dot -T svg -o g.svg g.dot
</code></pre>
<p>Example <code>dot</code> file.</p>
<pre><code class="language-dot">// file: g.dot
digraph {
    // Render ranks from left to right.
    rankdir=LR
    // Make background transparent.
    bgcolor=transparent

    // Global node attributes.
    node [shape=box]
    // Global edge attributes.
    edge [style=dotted,color=red]

    // Add nodes &amp; edge.
    stage1 -&gt; stage2
    // Add multiple edges at once.
    stage2 -&gt; { stage3_1, stage3_2 }
    // Add edge with custom attributes.
    stage3_2 -&gt; stage4 [label=&quot;some text&quot;]

    // Set custom attributes for specific node.
    stage4 [color=green,fillcolor=lightgray,style=&quot;filled,dashed&quot;,label=&quot;s4&quot;]

    // Create a subgraph. This can be used to group nodes/edges or as scope for
    // global node/edge attributes.
    // If the name starts with 'cluster' a border is drawn.
    subgraph cluster_1 {
        stage5_1
        stage5_2
    }

    // Add some edges to subgraph nodes.
    stage3_1 -&gt; { stage5_1, stage5_2 }
}
</code></pre>
<p>Rendered <code>svg</code> file.
<img src="tools/assets/g.svg" alt="g.svg" /></p>
<h2 id="references-1"><a class="header" href="#references-1">References</a></h2>
<ul>
<li><a href="https://graphviz.org/doc/info/lang.html">DOT language</a></li>
<li><a href="https://graphviz.org/doc/info/attrs.html">Attributes</a></li>
<li><a href="https://graphviz.org/doc/info/shapes.html">Node shapes</a></li>
<li><a href="https://graphviz.org/doc/info/colors.html">Colors</a></li>
<li><a href="https://graphviz.org/pdf/dotguide.pdf">User manual</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="resource-analysis--monitor"><a class="header" href="#resource-analysis--monitor">Resource analysis &amp; monitor</a></h1>
<ul>
<li><a href="monitor/./lsof.html">lsof</a></li>
<li><a href="monitor/./ss.html">ss</a></li>
<li><a href="monitor/./pidstat.html">pidstat</a></li>
<li><a href="monitor/./pgrep.html">pgrep</a></li>
<li><a href="monitor/./pmap.html">pmap</a></li>
<li><a href="monitor/./pstack.html">pstack</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="lsof8"><a class="header" href="#lsof8">lsof(8)</a></h1>
<pre><code class="language-markdown">lsof
  -r &lt;s&gt; ..... repeatedly execute command ervery &lt;s&gt; seconds
  -a ......... AND slection filters instead ORing (OR: default)
  -p &lt;pid&gt; ... filter by &lt;pid&gt;
  +fg ........ show file flags for file descripros
  -n ......... don't convert network addr to hostnames
  -P ......... don't convert network port to service names
  -i &lt;@h[:p]&gt;. show connections to h (hostname|ip addr) with optional port p
  -s &lt;p:s&gt; ... in conjunction with '-i' filter for protocol &lt;p&gt; in state &lt;s&gt;
  -U ......... show unix domain sockets ('@' indicates abstract sock name, see unix(7))
</code></pre>
<pre><code class="language-markdown">file flags:
  R/W/RW ..... read/write/read-write
  CR ......... create
  AP ......... append
  TR ......... truncate
</code></pre>
<pre><code class="language-markdown">-s protocols
  TCP, UDP

-s states (TCP)
  CLOSED, IDLE, BOUND, LISTEN, ESTABLISHED, SYN_SENT, SYN_RCDV, ESTABLISHED,
  CLOSE_WAIT, FIN_WAIT1, CLOSING, LAST_ACK, FIN_WAIT_2, TIME_WAIT

-s states (UDP)
  Unbound, Idle
</code></pre>
<h1 id="examples-4"><a class="header" href="#examples-4">Examples</a></h1>
<h2 id="file-flags"><a class="header" href="#file-flags">File flags</a></h2>
<p>Show open files with file flags for process:</p>
<pre><code class="language-markdown">lsof +fg -p &lt;pid&gt;
</code></pre>
<h2 id="open-tcp-connections"><a class="header" href="#open-tcp-connections">Open TCP connections</a></h2>
<p>Show open tcp connections for <code>$USER</code>:</p>
<pre><code class="language-markdown">lsof -a -u $USER -i TCP
</code></pre>
<p><strong>Note</strong>: <code>-a</code> <em>ands</em> the results. If <code>-a</code> is not given all open files matching
<code>$USER</code> and all tcp connections are listed (<em>ored</em>).</p>
<h2 id="open-connection-to-specific-host"><a class="header" href="#open-connection-to-specific-host">Open connection to specific host</a></h2>
<p>Show open connections to <code>localhost</code> for <code>$USER</code>:</p>
<pre><code class="language-markdown">lsof -a -u $USER -i @localhost
</code></pre>
<h2 id="open-connection-to-specific-port"><a class="header" href="#open-connection-to-specific-port">Open connection to specific port</a></h2>
<p>Show open connections to port <code>:1234</code> for <code>$USER</code>:</p>
<pre><code class="language-markdown">lsof -a -u $USER -i :1234
</code></pre>
<h2 id="ipv4-tcp-connections-in-established-state"><a class="header" href="#ipv4-tcp-connections-in-established-state">IPv4 TCP connections in <code>ESTABLISHED</code> state</a></h2>
<pre><code class="language-markdown">lsof -i 4TCP -s TCP:ESTABLISHED
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="ss8"><a class="header" href="#ss8">ss(8)</a></h1>
<pre><code class="language-markdown">ss [option] [filter]
</code></pre>
<pre><code class="language-markdown">[option]
  -p ..... Show process using socket
  -l ..... Show sockets in listening state
  -4/-6 .. Show IPv4/6 sockets
  -x ..... Show unix sockets
  -n ..... Show numeric ports (no resolve)
  -O ..... Oneline output per socket
</code></pre>
<pre><code class="language-markdown">[filter]
  dport/sport PORT .... Filter for destination/source port
  dst/src ADDR ........ Filter for destination/source address

  and/or .............. Logic operator
  ==/!= ............... Comparison operator

  (EXPR) .............. Group exprs
</code></pre>
<h1 id="examples-5"><a class="header" href="#examples-5">Examples</a></h1>
<p>Show all tcp IPv4 sockets connecting to port <code>443</code>:</p>
<pre><code class="language-markdown">ss -4 'dport 443'
</code></pre>
<p>Show all tcp IPv4 sockets that don't connect to port <code>443</code> or connect to address <code>1.2.3.4</code>.</p>
<pre><code class="language-markdown">ss -4 'dport != 443 or dst 1.2.3.4'
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="pidstat1"><a class="header" href="#pidstat1">pidstat(1)</a></h1>
<pre><code class="language-markdown">pidstat [opt] [interval] [cont]
  -U [user]     show username instead UID, optionally only show for user
  -r            memory statistics
  -d            I/O statistics
  -h            single line per process and no lines with average
</code></pre>
<h1 id="page-fault-and-memory-utilization"><a class="header" href="#page-fault-and-memory-utilization">Page fault and memory utilization</a></h1>
<pre><code class="language-markdown">pidstat -r -p &lt;pid&gt; [interval] [count]
</code></pre>
<pre><code class="language-markdown">minor_pagefault: Happens when the page needed is already in memory but not
                 allocated to the faulting process, in that case the kernel
                 only has to create a new page-table entry pointing to the
                 shared physical page (not required to load a memory page from
                 disk).

major_pagefault: Happens when the page needed is NOT in memory, the kernel
                 has to create a new page-table entry and populate the
                 physical page (required to load a memory page from disk).
</code></pre>
<h1 id="io-statistics"><a class="header" href="#io-statistics">I/O statistics</a></h1>
<pre><code class="language-markdown">pidstat -d -p &lt;pid&gt; [interval] [count]
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="pgrep1"><a class="header" href="#pgrep1">pgrep(1)</a></h1>
<pre><code class="language-markdown">pgrep [opts] &lt;pattern&gt;
  -n         only list newest matching process
  -u &lt;usr&gt;   only show matching for user &lt;usr&gt;
  -l         additionally list command
  -a         additionally list command + arguments
</code></pre>
<h2 id="debug-newest-process"><a class="header" href="#debug-newest-process">Debug newest process</a></h2>
<p>For example attach gdb to newest zsh process from <code>$USER</code>.</p>
<pre><code class="language-markdown">gdb -p $(pgrep -n -u $USER zsh)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="pmap1"><a class="header" href="#pmap1">pmap(1)</a></h1>
<pre><code class="language-markdown">pmap [opts] &lt;pid&gt;
    Dump virtual memory map of process.
    Compared to /proc/&lt;pid&gt;/maps it shows the size of the mappings.
opts:
  -p         show full path in the mapping
  -x         show details (eg RSS usage of each segment)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="pstack1"><a class="header" href="#pstack1">pstack(1)</a></h1>
<pre><code class="language-markdown">pstack &lt;pid&gt;
    Dump stack for all threads of process.
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="trace-and-profile"><a class="header" href="#trace-and-profile">Trace and Profile</a></h1>
<ul>
<li><a href="trace_profile/./strace.html">strace</a></li>
<li><a href="trace_profile/./ltrace.html">ltrace</a></li>
<li><a href="trace_profile/./perf.html">perf</a></li>
<li><a href="trace_profile/./oprofile.html">OProfile</a></li>
<li><a href="trace_profile/./time.html">time</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="strace1"><a class="header" href="#strace1">strace(1)</a></h1>
<pre><code class="language-markdown">strace [opts] [prg]
  -f .......... follow child processes on fork(2)
  -p &lt;pid&gt; .... attach to running process
  -s &lt;size&gt; ... max string size, truncate of longer (default: 32)
  -e &lt;expr&gt; ... expression for trace filtering
  -o &lt;file&gt; ... log output into &lt;file&gt;
  -c .......... dump syscall statitics at the end
  -k .......... dump stack trace for each syscall
  -P &lt;path&gt; ... only trace syscall accesing path
  -y .......... print paths for FDs
  -tt ......... print absolute timestamp (with us precision)
  -r .......... print relative timestamp
</code></pre>
<pre><code class="language-markdown">&lt;expr&gt;:
  trace=syscall[,syscall] .... trace only syscall listed
  trace=file ................. trace all syscall that take a filename as arg
  trace=process .............. trace process management related syscalls
  trace=signal ............... trace signal related syscalls
  signal ..................... trace signals delivered to the process
</code></pre>
<h1 id="examples-6"><a class="header" href="#examples-6">Examples</a></h1>
<p>Trace <code>open(2)</code> &amp; <code>socket(2)</code> syscalls for a running process + child processes:</p>
<pre><code class="language-markdown">strace -f -e trace=open,socket -p &lt;pid&gt;
</code></pre>
<p>Trace signals delivered to a running process:</p>
<pre><code class="language-markdown">strace -e signal -e 'trace=!all' -p &lt;pid&gt;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="ltrace1"><a class="header" href="#ltrace1">ltrace(1)</a></h1>
<pre><code class="language-markdown">ltrace [opts] [prg]
  -f .......... follow child processes on fork(2)
  -p &lt;pid&gt; .... attach to running process
  -o &lt;file&gt; ... log output into &lt;file&gt;
  -l &lt;filter&gt; . show who calls into lib matched by &lt;filter&gt;
  -C .......... demangle
</code></pre>
<h1 id="example-5"><a class="header" href="#example-5">Example</a></h1>
<p>List which program/libs call into <code>libstdc++</code>:</p>
<pre><code class="language-bash">ltrace -l '*libstdc++*' -C -o ltrace.log ./main
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="perf1"><a class="header" href="#perf1">perf(1)</a></h1>
<pre><code class="language-markdown">perf list      show supported hw/sw events

perf stat
  -p &lt;pid&gt; .. show stats for running process
  -I &lt;ms&gt; ... show stats periodically over interval &lt;ms&gt;
  -e &lt;ev&gt; ... filter for events

perf top
  -p &lt;pid&gt; .. show stats for running process
  -F &lt;hz&gt; ... sampling frequency
  -K ........ hide kernel threads

perf record
  -p &lt;pid&gt; ............... record stats for running process
  -F &lt;hz&gt; ................ sampling frequency
  --call-graph &lt;method&gt; .. [fp, dwarf, lbr] method how to caputre backtrace
                           fp   : use frame-pointer, need to compile with
                                  -fno-omit-frame-pointer
                           dwarf: use .cfi debug information
                           lbr  : use hardware last branch record facility
  -g ..................... short-hand for --call-graph fp
  -e &lt;ev&gt; ................ filter for events

perf report
  -n .................... annotate symbols with nr of samples
  --stdio ............... report to stdio, if not presen tui mode
  -g graph,0.5,caller ... show caller based call chains with value &gt;0.5
</code></pre>
<pre><code class="language-markdown">Useful &lt;ev&gt;:
  page-faults
  minor-faults
  major-faults
  cpu-cycles`
  task-clock
</code></pre>
<h2 id="flamegraph"><a class="header" href="#flamegraph"><a href="https://github.com/brendangregg/FlameGraph"><code>Flamegraph</code></a></a></h2>
<h3 id="flamegraph-with-single-event-trace"><a class="header" href="#flamegraph-with-single-event-trace">Flamegraph with single event trace</a></h3>
<pre><code class="language-markdown">perf record -g -e cpu-cycles -p &lt;pid&gt;
perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl &gt; cycles-flamegraph.svg
</code></pre>
<h3 id="flamegraph-with-multiple-event-traces"><a class="header" href="#flamegraph-with-multiple-event-traces">Flamegraph with multiple event traces</a></h3>
<pre><code class="language-markdown">perf record -g -e cpu-cycles,page-faults -p &lt;pid&gt;
perf script --per-event-dump
# fold &amp; generate as above
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="oprofile"><a class="header" href="#oprofile"><a href="https://oprofile.sourceforge.io/">OProfile</a></a></h1>
<pre><code class="language-markdown">operf -g -p &lt;pid&gt;
  -g ...... caputre call-graph information

opreport [opt] FILE
            show time spent per binary image
  -l ...... show time spent per symbol
  -c ...... show callgraph information (see below)
  -a ...... add column with time spent accumulated over child nodes

ophelp      show supported hw/sw events
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="usrbintime1"><a class="header" href="#usrbintime1">/usr/bin/time(1)</a></h1>
<pre><code class="language-markdown"># statistics of process run
/usr/bin/time -v &lt;cmd&gt;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="binary"><a class="header" href="#binary">Binary</a></h1>
<ul>
<li><a href="binary/./od.html">od</a></li>
<li><a href="binary/./xxd.html">xxd</a></li>
<li><a href="binary/./readelf.html">readelf</a></li>
<li><a href="binary/./objdump.html">objdump</a></li>
<li><a href="binary/./nm.html">nm</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="od1"><a class="header" href="#od1">od(1)</a></h1>
<pre><code class="language-markdown">  od [opts] &lt;file&gt;
    -An         don't print addr info
    -tx4        print hex in 4 byte chunks
    -ta         print as named character
    -tc         printable chars or backslash escape
    -w4         print 4 bytes per line
    -j &lt;n&gt;      skip &lt;n&gt; bytes from &lt;file&gt; (hex if start with 0x)
    -N &lt;n&gt;      dump &lt;n&gt; bytes (hex of start with 0x)
</code></pre>
<h2 id="ascii-to-hex-string"><a class="header" href="#ascii-to-hex-string">ASCII to hex string</a></h2>
<pre><code class="language-markdown">  echo -n AAAABBBB | od -An -w4 -tx4
    &gt;&gt; 41414141
    &gt;&gt; 42424242

  echo -n '\x7fELF\n' | od -tx1 -ta -tc
    &gt;&gt; 0000000  7f  45  4c  46  0a      # tx1
    &gt;&gt;         del   E   L   F  nl      # ta
    &gt;&gt;         177   E   L   F  \n      # tc
</code></pre>
<h2 id="extract-parts-of-file"><a class="header" href="#extract-parts-of-file">Extract parts of file</a></h2>
<p>For example <code>.rodata</code> section from an elf file. We can use <code>readelf</code> to get the
offset into the file where the <code>.rodata</code> section starts.</p>
<pre><code class="language-markdown">  readelf -W -S foo
    &gt;&gt; Section Headers:
    &gt;&gt; [Nr] Name              Type            Address          Off    Size   ES Flg Lk Inf Al
    &gt;&gt; ...
    &gt;&gt; [15] .rodata           PROGBITS        00000000004009c0 0009c0 000030 00   A  0   0 16
</code></pre>
<p>With the offset of <code>-j 0x0009c0</code> we can dump <code>-N 0x30</code> bytes from the beginning of
the <code>.rodata</code> section as follows:</p>
<pre><code class="language-markdown">  od -j 0x0009c0 -N 0x30 -tx4 -w4 foo
    &gt;&gt; 0004700 00020001
    &gt;&gt; 0004704 00000000
    &gt;&gt; *
    &gt;&gt; 0004740 00000001
    &gt;&gt; 0004744 00000002
    &gt;&gt; 0004750 00000003
    &gt;&gt; 0004754 00000004
</code></pre>
<p><strong>Note</strong>: Numbers starting with <code>0x</code> will be interpreted as hex by <code>od</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="xxd1"><a class="header" href="#xxd1">xxd(1)</a></h1>
<pre><code class="language-markdown">  xxd [opts]
    -p          dump continuous hexdump
    -r          convert hexdump into binary ('revert')
    -e          dump as little endian mode
    -i          output as C array
</code></pre>
<h2 id="ascii-to-hex-stream"><a class="header" href="#ascii-to-hex-stream">ASCII to hex stream</a></h2>
<pre><code class="language-markdown">  echo -n 'aabb' | xxd -p
    &gt;&gt; 61616262
</code></pre>
<h2 id="hex-to-binary-stream"><a class="header" href="#hex-to-binary-stream">Hex to binary stream</a></h2>
<pre><code class="language-markdown">  echo -n '61616262' | xxd -p -r
    &gt;&gt; aabb
</code></pre>
<h2 id="ascii-to-binary"><a class="header" href="#ascii-to-binary">ASCII to binary</a></h2>
<pre><code class="language-markdown">  echo -n '\x7fELF' | xxd -p | xxd -p -r | file -p -
    &gt;&gt; ELF
</code></pre>
<h2 id="ascii-to-c-array-hex-encoded"><a class="header" href="#ascii-to-c-array-hex-encoded">ASCII to <code>C</code> array (hex encoded)</a></h2>
<pre><code class="language-markdown">  xxd -i &lt;(echo -n '\x7fELF')
    &gt;&gt; unsigned char _proc_self_fd_11[] = {
    &gt;&gt;   0x7f, 0x45, 0x4c, 0x46
    &gt;&gt; };
    &gt;&gt; unsigned int _proc_self_fd_11_len = 4;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="readelf1"><a class="header" href="#readelf1">readelf(1)</a></h1>
<pre><code class="language-markdown">  readelf [opts] &lt;elf&gt;
    -W|--wide     wide output, dont break output at 80 chars
    -h            print ELF header
    -S            print section headers
    -l            print program headers + segment mapping
    -d            print .dynamic section (dynamic link information)
    --syms        print symbol tables (.symtab .dynsym)
    --dyn-syms    print dynamic symbol table (exported symbols for dynamic linker)
    -r            print relocation sections (.rel.*, .rela.*)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="objdump1"><a class="header" href="#objdump1">objdump(1)</a></h1>
<pre><code class="language-markdown">  objdump [opts] &lt;elf&gt;
    -M intel                use intil syntax
    -d                      disassemble text section
    -D                      disassemble all sections
    -S                      mix disassembly with source code
    -C                      demangle
    -j &lt;section&gt;            display info for section
    --[no-]show-raw-insn    [dont] show object code next to disassembly
</code></pre>
<h2 id="disassemble-section"><a class="header" href="#disassemble-section">Disassemble section</a></h2>
<p>For example <code>.plt</code> section:</p>
<pre><code class="language-markdown">  objdump -j .plt -d &lt;elf&gt;
</code></pre>
<h2 id="example-disassemble-raw-binary"><a class="header" href="#example-disassemble-raw-binary">Example: disassemble raw binary</a></h2>
<p>This can be helpful for example as a cheap analysis tool when toying with JIT
generating code. We could just write thee binary code buffer to a file and
disassemble with <code>objdump</code>.</p>
<p>To re-create that case, we just assemble and link some ELF file and then create
a raw binary of the text section with <code>objcopy</code>.</p>
<pre><code class="language-x86asm"># file: test.s
.section .text, &quot;ax&quot;

.global _start
_start:
    xor %rax, %rax
    mov $0x8, %rax
1:
    cmp $0, %rax
    je 2f
    dec %rax
    jmp 1b
2:
    # x86-64 exit(2) syscall
    mov $0, %rdi
    mov $60, %rax
    syscall
</code></pre>
<pre><code class="language-bash"># Assemble &amp; link.
as -o test.o test.s
ld -o test test.o testc.o
# ELF -&gt; binary (only take .text section).
objcopy -O binary --only-section .text test test-bin

# Disassemble raw binary.
objdump -D -b binary -m i386:x86-64 test-bin
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="nm1"><a class="header" href="#nm1">nm(1)</a></h1>
<pre><code class="language-markdown">  nm [opts] &lt;elf&gt;
    -C          demangle
    -u          undefined only
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="development"><a class="header" href="#development">Development</a></h1>
<ul>
<li><a href="development/./c++filt.html">c++filt</a></li>
<li><a href="development/./c++.html">c++</a></li>
<li><a href="development/./glibc.html">glibc</a></li>
<li><a href="development/./gcc.html">gcc</a></li>
<li><a href="development/./make.html">make</a></li>
<li><a href="development/./ld.so.html">ld.so</a></li>
<li><a href="development/./symbolver.html">symbol versioning</a></li>
<li><a href="development/./python.html">python</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="cfilt1"><a class="header" href="#cfilt1">c++filt(1)</a></h1>
<h2 id="demangle-symbol"><a class="header" href="#demangle-symbol">Demangle symbol</a></h2>
<pre><code class="language-markdown">  c++-filt &lt;symbol_str&gt;
</code></pre>
<h2 id="demangle-stream"><a class="header" href="#demangle-stream">Demangle stream</a></h2>
<p>For example dynamic symbol table:</p>
<pre><code class="language-markdown">  readelf -W --dyn-syms &lt;elf&gt; | c++filt
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="c"><a class="header" href="#c">c++</a></h1>
<h2 id="type-deduction"><a class="header" href="#type-deduction">Type deduction</a></h2>
<p>Force compile error to see what <code>auto</code> is deduced to.</p>
<pre><code class="language-cpp">auto foo = bar();

// force compile error
typename decltype(foo)::_;
</code></pre>
<h2 id="variadic-templates-parameter-pack"><a class="header" href="#variadic-templates-parameter-pack">Variadic templates (<a href="https://en.cppreference.com/w/cpp/language/parameter_pack">parameter pack</a>)</a></h2>
<pre><code class="language-cpp">#include &lt;iostream&gt;

// -- Example 1 - print template value arguments.

// Base case with one parameter.
template&lt;int P&gt;
void show_int() {
    printf(&quot;%d\n&quot;, P);
}

// General case with at least two parameters, to disambiguate from base case.
template&lt;int P0, int P1, int... Params&gt;
void show_int() {
    printf(&quot;%d, &quot;, P0);
    show_int&lt;P1, Params...&gt;();
}

// -- Example 2 - print values of different types.

// Base case with one parameter.
template&lt;typename T&gt;
void show(const T&amp; t) {
    std::cout &lt;&lt; t &lt;&lt; '\n';
}

// General case with at least two parameters, to disambiguate from base case.
template&lt;typename T0, typename T1, typename... Types&gt;
void show(const T0&amp; t0, const T1&amp; t1, const Types&amp;... types) {
    std::cout &lt;&lt; t0 &lt;&lt; &quot;, &quot;;
    show(t1, types...);
}

int main() {
    show_int&lt;1, 2, 3, 4, 5&gt;();
    show(1, 1.0, &quot;foo&quot;, 'a');
}
</code></pre>
<h2 id="example-any_of-template-meta-function"><a class="header" href="#example-any_of-template-meta-function">Example: <code>any_of</code> template meta function</a></h2>
<pre><code class="language-cpp">#include &lt;type_traits&gt;

template&lt;typename T, typename... U&gt;
struct any_of : std::false_type {};

// Found our type T in the list of types U.
template&lt;typename T, typename... U&gt;
struct any_of&lt;T, T, U...&gt; : std::true_type {};

// Pop off the first element in the list of types U,
// since it didn't match our type T.
template&lt;typename T, typename U0, typename... U&gt;
struct any_of&lt;T, U0, U...&gt; : any_of&lt;T, U...&gt; {};

// Convenience template variable to invoke meta function.
template&lt;typename T, typename... U&gt;
constexpr bool any_of_v = any_of&lt;T, U...&gt;::value;

static_assert(any_of_v&lt;int, char, bool, int&gt;, &quot;&quot;);
static_assert(!any_of_v&lt;int, char, bool, float&gt;, &quot;&quot;);
</code></pre>
<h2 id="example-sfinae-enable_if"><a class="header" href="#example-sfinae-enable_if">Example: <a href="https://en.cppreference.com/w/cpp/language/sfinae">SFINAE</a> (<a href="https://en.cppreference.com/w/cpp/types/enable_if">enable_if</a>)</a></h2>
<p>Provide a single entry point <code>Invoke</code> to call some <code>Operations</code>.
Use <code>enable_if</code> to enable/disable the template functions depending on the two
available traits an operation can have:</p>
<ul>
<li>Operation returns a result</li>
<li>Operation requires a context</li>
</ul>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;type_traits&gt;

// Helper meta fns.

template&lt;typename T&gt;
using enable_if_bool = std::enable_if_t&lt;T::value, bool&gt;;

template&lt;typename T&gt;
using disable_if_bool = std::enable_if_t&lt;!T::value, bool&gt;;

template&lt;typename T&gt;
using has_dst = std::integral_constant&lt;bool, !std::is_same&lt;typename T::Return, void&gt;::value&gt;;

// Template meta programming invoke machinery.

namespace impl {
    // Invoke an OPERATION which *USES* a context.
    template&lt;typename Ctx, template&lt;typename&gt; class Op, typename... P,
             enable_if_bool&lt;typename Op&lt;Ctx&gt;::HasCtx&gt; = true&gt;
    typename Op&lt;Ctx&gt;::Return Invoke(const Ctx&amp; C, P... params) {
        return Op&lt;Ctx&gt;()(C, params...);
    }

    // Invoke an OPERATION which uses *NO* context.
    template&lt;typename Ctx, template&lt;typename&gt; class Op, typename... P,
             disable_if_bool&lt;typename Op&lt;Ctx&gt;::HasCtx&gt; = true&gt;
    typename Op&lt;Ctx&gt;::Return Invoke(const Ctx&amp;, P... params) {
        return Op&lt;Ctx&gt;()(params...);
    }
}  // namespace impl

// Invoke an OPERATION which *HAS* a DESTINATION with arbitrary number of arguments.
template&lt;typename Ctx, template&lt;typename&gt; class Op, typename... P,
         enable_if_bool&lt;has_dst&lt;Op&lt;Ctx&gt;&gt;&gt; = true&gt;
void Invoke(const Ctx&amp; C, P... params) {
    std::cout &lt;&lt; &quot;Invoke &quot; &lt;&lt; Op&lt;Ctx&gt;::Name &lt;&lt; '\n';
    typename Op&lt;Ctx&gt;::Return R = impl::Invoke&lt;Ctx, Op&gt;(C, params...);
    std::cout &lt;&lt; &quot;returned -&gt; &quot; &lt;&lt; R &lt;&lt; '\n';
}

// Invoke an OPERATION which has *NOT* a DESTINATION with arbitrary number of arguments.
template&lt;typename Ctx, template&lt;typename&gt; class Op, typename... P,
         disable_if_bool&lt;has_dst&lt;Op&lt;Ctx&gt;&gt;&gt; = true&gt;
void Invoke(const Ctx&amp; C, P... params) {
    std::cout &lt;&lt; &quot;Invoke &quot; &lt;&lt; Op&lt;Ctx&gt;::Name &lt;&lt; &quot; without destination.&quot; &lt;&lt; '\n';
    impl::Invoke&lt;Ctx, Op&gt;(C, params...);
}

// Custom context.

struct Ctx {
    void out(const char* s, unsigned v) const { printf(&quot;%s%x\n&quot;, s, v); }
};

// Operations to invoke.

template&lt;typename Ctx&gt;
struct OpA {
    using HasCtx = std::false_type;
    using Return = int;
    static constexpr const char* const Name = &quot;OpA&quot;;

    constexpr Return operator()(int a, int b) const { return a + b; }
};

template&lt;typename Ctx&gt;
struct OpB {
    using HasCtx = std::true_type;
    using Return = void;
    static constexpr const char* const Name = &quot;OpB&quot;;

    Return operator()(const Ctx&amp; C, unsigned a) const { C.out(&quot;a = &quot;, a); }
};

int main() {
    Ctx C;

    Invoke&lt;Ctx, OpA&gt;(C, 1, 2);
    Invoke&lt;Ctx, OpB&gt;(C, 0xf00du);

    return 0;
}
</code></pre>
<h2 id="example-minimal-templatized-test-registry"><a class="header" href="#example-minimal-templatized-test-registry">Example: Minimal templatized test registry</a></h2>
<p>A small test function registry bringing together a few different template
features.</p>
<pre><code class="language-cpp">#include &lt;cstdio&gt;
#include &lt;functional&gt;
#include &lt;map&gt;
#include &lt;string&gt;
#include &lt;type_traits&gt;

template&lt;typename R, typename... P&gt;
struct registry {
    using FUNC = R (*)(P...);
    using SELF = registry&lt;R, P...&gt;;
    using RET = R;

    static SELF&amp; get() {
        static SELF r;
        return r;
    }

    bool add(std::string nm, FUNC fn) {
        const auto r = m_fns.insert({std::move(nm), std::move(fn)});
        return r.second;
    }

    R invoke(const std::string&amp; nm, P... p) const { return invoke_impl&lt;R&gt;(nm, p...); }

    void dump() const {
        for (const auto&amp; it : m_fns) {
            std::puts(it.first.c_str());
        }
    }

  private:
    std::map&lt;std::string, FUNC&gt; m_fns;

    template&lt;typename RET&gt;
    std::enable_if_t&lt;std::is_same_v&lt;RET, void&gt;&gt; invoke_impl(const std::string&amp; nm, P... p) const {
        const auto it = m_fns.find(nm);
        if (it == m_fns.end()) {
            return;
        }
        std::invoke(it-&gt;second, p...);
    }

    template&lt;typename RET&gt;
    std::enable_if_t&lt;!std::is_same_v&lt;RET, void&gt;, RET&gt; invoke_impl(const std::string&amp; nm,
                                                                  P... p) const {
        const auto it = m_fns.find(nm);
        if (it == m_fns.end()) {
            static_assert(std::is_default_constructible_v&lt;RET&gt;,
                          &quot;RET must be default constructible&quot;);
            return {};
        }
        return std::invoke(it-&gt;second, p...);
    }
};

#define TEST_REGISTER(REGISTRY, NAME)                                                      \
    static bool regfn_##REGISTRY##NAME() {                                                 \
        const bool r = REGISTRY::get().add(#NAME, NAME);                                   \
        if (!r) {                                                                          \
            std::puts(&quot;Failed to register test &quot; #NAME &quot;, same name already registered!&quot;); \
            std::abort();                                                                  \
        }                                                                                  \
        return r;                                                                          \
    }                                                                                      \
    static const bool reg_##REGISTRY##NAME = regfn_##REGISTRY##NAME();

#define TEST(REGISTRY, NAME, ...)    \
    REGISTRY::RET NAME(__VA_ARGS__); \
    TEST_REGISTER(REGISTRY, NAME);   \
    REGISTRY::RET NAME(__VA_ARGS__)

// -- Usage 1 simple usage.

using REG1 = registry&lt;void&gt;;
TEST(REG1, test1) {
    std::puts(&quot;REG1::test1&quot;);
}
TEST(REG1, test2) {
    std::puts(&quot;REG1::test2&quot;);
}

// -- Usage 2 with convenience macro wrapper.

using REG2 = registry&lt;void, bool&gt;;
#define TEST2(NAME, ...) TEST(REG2, NAME, ##__VA_ARGS__)

TEST2(test1, bool val) {
    printf(&quot;REG2::test1 val %d\n&quot;, val);
}

int main() {
    const auto&amp; R1 = REG1::get();
    R1.dump();
    R1.invoke(&quot;test1&quot;);
    R1.invoke(&quot;test2&quot;);

    const auto&amp; R2 = REG2::get();
    R2.dump();
    R2.invoke(&quot;test1&quot;, true);

    return 0;
}
</code></pre>
<h2 id="example-concepts-pre-c20"><a class="header" href="#example-concepts-pre-c20">Example: Concepts pre c++20</a></h2>
<p>Prior to c++20's concepts, <code>SFINAE</code> and <code>std::void_t</code> can be leveraged to build
something similar allowing to define an interface (aka trait) for a template
parameter.</p>
<pre><code class="language-cpp">
template&lt;typename T, template&lt;typename&gt; class Checker, typename = void&gt;
struct is_valid : std::false_type {};

template&lt;typename T, template&lt;typename&gt; class Checker&gt;
struct is_valid&lt;T, Checker, std::void_t&lt;Checker&lt;T&gt;&gt;&gt; : std::true_type {};

template&lt;typename T, template&lt;typename&gt; class Checker&gt;
static constexpr bool is_valid_v = is_valid&lt;T, Checker&gt;::value;

// -----------------------------------------------------------------------------

template&lt;typename T, typename R, template&lt;typename&gt; class Checker, typename = void&gt;
struct is_valid_with_ret : std::false_type {};

template&lt;typename T, typename R, template&lt;typename&gt; class Checker&gt;
struct is_valid_with_ret&lt;T, R, Checker, std::void_t&lt;Checker&lt;T&gt;&gt;&gt; : std::is_same&lt;R, Checker&lt;T&gt;&gt; {};

template&lt;typename T, typename R, template&lt;typename&gt; class Checker&gt;
static constexpr bool is_valid_with_ret_v = is_valid_with_ret&lt;T, R, Checker&gt;::value;

// -----------------------------------------------------------------------------

template&lt;typename T&gt;
struct is_entry {
    template&lt;typename TT&gt;
    using init = decltype(std::declval&lt;TT&gt;().init());
    template&lt;typename TT&gt;
    using tag = decltype(std::declval&lt;TT&gt;().tag());
    template&lt;typename TT&gt;
    using val = decltype(std::declval&lt;TT&gt;().val());

    static constexpr bool value = is_valid_v&lt;T, init&gt; &amp;&amp;
                                  is_valid_with_ret_v&lt;T, int, tag&gt; &amp;&amp;
                                  is_valid_with_ret_v&lt;T, typename T::Type, val&gt;;
};

template&lt;typename T&gt;
static constexpr bool is_entry_v = is_entry&lt;T&gt;::value;

template&lt;typename E&gt;
struct Entry {
    using Type = E;
    void init();
    int tag() const;
    E val() const;
};

int main() {
    static_assert(is_entry_v&lt;Entry&lt;bool&gt;&gt;, &quot;&quot;);
}
</code></pre>
<p>The main mechanic can be explained with the following reduced example. If one
of the <code>decltype(std:declval&lt;T&gt;...</code> expressions is ill-formed, the template
specialization for <code>is_valid</code> will be removed from the candidate set due to
<a href="https://en.cppreference.com/w/cpp/language/sfinae">SFINAE</a>.</p>
<pre><code class="language-cpp">template&lt;typename T, typename = void&gt;
struct is_valid : std::false_type {};

template&lt;typename T&gt;
struct is_valid&lt;T, std::void_t&lt;
                       decltype(std::declval&lt;T&gt;().some_fun1()),
                       decltype(std::declval&lt;T&gt;().some_fun2())
               &gt;&gt; : std::true_type {};
</code></pre>
<blockquote>
<p><code>std::declval&lt;T&gt;()</code> creates an instance of type T in an unevaluated context.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="glibc"><a class="header" href="#glibc">glibc</a></h1>
<h2 id="malloc-tracer-mtrace3"><a class="header" href="#malloc-tracer-mtrace3">malloc tracer <a href="http://man7.org/linux/man-pages/man3/mtrace.3.html"><code>mtrace(3)</code></a></a></h2>
<p>Trace memory allocation and de-allocation to detect memory leaks.
Need to call <code>mtrace(3)</code> to install the tracing hooks.</p>
<p>If we can't modify the binary to call <code>mtrace</code> we can create a small shared
library and pre-load it.</p>
<pre><code class="language-c">// libmtrace.c
#include &lt;mcheck.h&gt;
__attribute__((constructor))  static void init_mtrace() { mtrace(); }
</code></pre>
<p>Compile as:</p>
<pre><code class="language-bash">gcc -shared -fPIC -o libmtrace.so libmtrace.c
</code></pre>
<p>To generate the trace file run:</p>
<pre><code class="language-bash">export MALLOC_TRACE=&lt;file&gt;
LD_PRELOAD=./libmtrace.so &lt;binary&gt;
</code></pre>
<p><strong>Note</strong>: If <code>MALLOC_TRACE</code> is not set <code>mtrace</code> won't install tracing hooks.</p>
<p>To get the results of the trace file:</p>
<pre><code class="language-bash">mtrace &lt;binary&gt; $MALLOC_TRACE
</code></pre>
<h2 id="malloc-check-mallopt3"><a class="header" href="#malloc-check-mallopt3">malloc check <a href="http://man7.org/linux/man-pages/man3/mallopt.3.html"><code>mallopt(3)</code></a></a></h2>
<p>Configure action when glibc detects memory error.</p>
<pre><code class="language-bash">export MALLOC_CHECK_=&lt;N&gt;
</code></pre>
<p>Useful values:</p>
<pre><code class="language-markdown">1   print detailed error &amp; continue
3   print detailed error + stack trace + memory mappings &amp; abort
7   print simple error message + stack trace + memory mappings &amp; abort
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gcc1"><a class="header" href="#gcc1">gcc(1)</a></h1>
<h2 id="cli-2"><a class="header" href="#cli-2">CLI</a></h2>
<h3 id="preprocessing"><a class="header" href="#preprocessing">Preprocessing</a></h3>
<p>While debugging can be helpful to just pre-process files.</p>
<pre><code class="language-bash">gcc -E [-dM] ...
</code></pre>
<ul>
<li><code>-E</code> run only preprocessor</li>
<li><code>-dM</code> list only <code>#define</code> statements</li>
<li><code>-###</code> dry-run, outputting exact compiler/linker invocations</li>
<li><code>-print-multi-lib</code> print available multilib configurations</li>
</ul>
<h3 id="target-options"><a class="header" href="#target-options">Target options</a></h3>
<pre><code class="language-bash"># List all target options with their description.
gcc --help=target

# Configure for current cpu arch and query (-Q) value of options.
gcc -march=native -Q --help=target
</code></pre>
<h2 id="builtins"><a class="header" href="#builtins"><a href="https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html">Builtins</a></a></h2>
<h3 id="__builtin_expectexpr-cond"><a class="header" href="#__builtin_expectexpr-cond"><code>__builtin_expect(expr, cond)</code></a></h3>
<p>Give the compiler a hint which branch is hot, so it can lay out the code
accordingly to reduce number of jump instructions.
See on <a href="https://godbolt.org/z/MbTHAP">compiler explorer</a>.</p>
<p>The semantics of this hint are as follows, the compiler prioritises <code>expr == cond</code>. So <code>__builtin_expect(expr, 0)</code> means that we expect the <code>expr</code> to be <code>0</code>
most of the time.</p>
<pre><code class="language-bash">echo &quot;
extern void foo();
extern void bar();
void run0(int x) {
  if (__builtin_expect(x,0)) { foo(); }
  else { bar(); }
}
void run1(int x) {
  if (__builtin_expect(x,1)) { foo(); }
  else { bar(); }
}
&quot; | gcc -O2 -S -masm=intel -o /dev/stdout -xc -
</code></pre>
<p>Will generate something similar to the following.</p>
<ul>
<li><code>run0</code>: <code>bar</code> is on the path without branch</li>
<li><code>run1</code>: <code>foo</code> is on the path without branch</li>
</ul>
<pre><code class="language-x86asm">run0:
        test    edi, edi
        jne     .L4
        xor     eax, eax
        jmp     bar
.L4:
        xor     eax, eax
        jmp     foo
run1:
        test    edi, edi
        je      .L6
        xor     eax, eax
        jmp     foo
.L6:
        xor     eax, eax
        jmp     bar
</code></pre>
<h2 id="abi-linux"><a class="header" href="#abi-linux">ABI (Linux)</a></h2>
<ul>
<li>C ABI - <a href="https://www.uclibc.org/docs/psABI-x86_64.pdf">SystemV ABI</a></li>
<li>C++ ABI - <a href="https://itanium-cxx-abi.github.io/cxx-abi">C++ Itanium ABI</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="make1"><a class="header" href="#make1">make(1)</a></h1>
<h2 id="anatomy-of-make-rules"><a class="header" href="#anatomy-of-make-rules">Anatomy of <code>make</code> rules</a></h2>
<pre><code class="language-make">target .. : prerequisite ..
	recipe
	..
</code></pre>
<ul>
<li><code>target</code>: an output generated by the rule</li>
<li><code>prerequisite</code>: an input that is used to generate the target</li>
<li><code>recipe</code>: list of actions to generate the output from the input</li>
</ul>
<blockquote>
<p>Use <code>make -p</code> to print all rules and variables (implicitly + explicitly defined).</p>
</blockquote>
<h2 id="pattern-rules--automatic-variables"><a class="header" href="#pattern-rules--automatic-variables">Pattern rules &amp; Automatic variables</a></h2>
<h3 id="pattern-rules"><a class="header" href="#pattern-rules">Pattern rules</a></h3>
<p>A pattern rule contains the <code>%</code> char (exactly one of them) and look like this example:</p>
<pre><code class="language-make">%.o : %.c
	$(CC) -c $(CFLAGS) $(CPPFLAGS) $&lt; -o $@
</code></pre>
<p>The target matches files of the pattern <code>%.o</code>, where <code>%</code> matches any none-empty
substring and other character match just them self.</p>
<p>The substring matched by <code>%</code> is called the <code>stem</code>.</p>
<p><code>%</code> in the prerequisite stands for the matched <code>stem</code> in the target.</p>
<h3 id="automatic-variables"><a class="header" href="#automatic-variables">Automatic variables</a></h3>
<p>As targets and prerequisites in pattern rules can't be spelled explicitly in
the recipe, make provides a set of automatic variables to work with:</p>
<ul>
<li><code>$@</code>: Name of the target that triggered the rule.</li>
<li><code>$&lt;</code>: Name of the first prerequisite.</li>
<li><code>$^</code>: Names of all prerequisites (without duplicates).</li>
<li><code>$+</code>: Names of all prerequisites (with duplicates).</li>
<li><code>$*</code>: Stem of the pattern rule.</li>
</ul>
<pre><code class="language-make"># file: Makefile

all: foobar blabla

foo% bla%: aaa bbb bbb
	@echo &quot;@ = $@&quot;
	@echo &quot;&lt; = $&lt;&quot;
	@echo &quot;^ = $^&quot;
	@echo &quot;+ = $+&quot;
	@echo &quot;* = $*&quot;
	@echo &quot;----&quot;

aaa:
bbb:
</code></pre>
<p>Running above <code>Makefile</code> gives:</p>
<pre><code class="language-test">@ = foobar
&lt; = aaa
^ = aaa bbb
+ = aaa bbb bbb
* = bar
----
@ = blabla
&lt; = aaa
^ = aaa bbb
+ = aaa bbb bbb
* = bla
----
</code></pre>
<p>Variables related to filesystem paths:</p>
<ul>
<li><code>$(CURDIR)</code>: Path of current working dir after using <code>make -C path</code></li>
</ul>
<h2 id="useful-functions"><a class="header" href="#useful-functions">Useful functions</a></h2>
<h3 id="substitution-references"><a class="header" href="#substitution-references">Substitution references</a></h3>
<p>Substitute strings matching pattern in a list.</p>
<pre><code class="language-make">in  := a.o l.a c.o
out := $(in:.o=.c)
# =&gt; out = a.c l.a c.c
</code></pre>
<h3 id="filter"><a class="header" href="#filter"><code>filter</code></a></h3>
<p>Keep strings matching a pattern in a list.</p>
<pre><code class="language-make">in  := a.a b.b c.c d.d
out := $(filter %.b %.c, $(in))
# =&gt; out = b.b c.c
</code></pre>
<h3 id="filter-out"><a class="header" href="#filter-out"><code>filter-out</code></a></h3>
<p>Remove strings matching a pattern from a list.</p>
<pre><code class="language-make">in  := a.a b.b c.c d.d
out := $(filter-out %.b %.c, $(in))
# =&gt; out = a.a d.d
</code></pre>
<h3 id="abspath"><a class="header" href="#abspath"><code>abspath</code></a></h3>
<p>Resolve each file name as absolute path (don't resolve symlinks).</p>
<pre><code class="language-make">$(abspath fname1 fname2 ..)

### `realpath`
Resolve each file name as canonical path.
```make
$(realpath fname1 fname2 ..)
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="ldso8"><a class="header" href="#ldso8">ld.so(8)</a></h1>
<h2 id="environment-variables"><a class="header" href="#environment-variables">Environment Variables</a></h2>
<pre><code class="language-console">  LD_PRELOAD=&lt;l_so&gt;       colon separated list of libso's to be pre loaded
  LD_DEBUG=&lt;opts&gt;         comma separated list of debug options
          =help           list available options
          =libs           show library search path
          =files          processing of input files
          =symbols        show search path for symbol lookup
          =bindings       show against which definition a symbol is bound
</code></pre>
<h2 id="ld_preload-initialization-order-and-link-map"><a class="header" href="#ld_preload-initialization-order-and-link-map">LD_PRELOAD: Initialization Order and Link Map</a></h2>
<p>Libraries specified in <code>LD_PRELOAD</code> are loaded from <code>left-to-right</code> but
initialized from <code>right-to-left</code>.</p>
<pre><code class="language-markdown">  &gt; ldd ./main
    &gt;&gt; libc.so.6 =&gt; /usr/lib/libc.so.6

  &gt; LD_PRELOAD=liba.so:libb.so ./main
             --&gt;
      preloaded in this order
             &lt;--
      initialized in this order
</code></pre>
<p>The preload order determines:</p>
<ul>
<li>the order libraries are inserted into the <code>link map</code></li>
<li>the initialization order for libraries</li>
</ul>
<p>For the example listed above the resulting <code>link map</code> will look like the
following:</p>
<pre><code class="language-makrdown">  +------+    +------+    +------+    +------+
  | main | -&gt; | liba | -&gt; | libb | -&gt; | libc |
  +------+    +------+    +------+    +------+
</code></pre>
<p>This can be seen when running with <code>LD_DEBUG=files</code>:</p>
<pre><code class="language-makrdown">  &gt; LD_DEBUG=files LD_PRELOAD=liba.so:libb.so ./main
    # load order (-&gt; determines link map)
    &gt;&gt; file=liba.so [0];  generating link map
    &gt;&gt; file=libb.so [0];  generating link map
    &gt;&gt; file=libc.so.6 [0];  generating link map

    # init order
    &gt;&gt; calling init: /usr/lib/libc.so.6
    &gt;&gt; calling init: &lt;path&gt;/libb.so
    &gt;&gt; calling init: &lt;path&gt;/liba.so
    &gt;&gt; initialize program: ./main
</code></pre>
<p>To verify the <code>link map</code> order we let <code>ld.so</code> resolve the <code>memcpy(3)</code> libc
symbol (used in <em>main</em>) dynamically, while enabling <code>LD_DEBUG=symbols,bindings</code>
to see the resolving in action.</p>
<pre><code class="language-makrdown">  &gt; LD_DEBUG=symbols,bindings LD_PRELOAD=liba.so:libb.so ./main
    &gt;&gt; symbol=memcpy;  lookup in file=./main [0]
    &gt;&gt; symbol=memcpy;  lookup in file=&lt;path&gt;/liba.so [0]
    &gt;&gt; symbol=memcpy;  lookup in file=&lt;path&gt;/libb.so [0]
    &gt;&gt; symbol=memcpy;  lookup in file=/usr/lib/libc.so.6 [0]
    &gt;&gt; binding file ./main [0] to /usr/lib/libc.so.6 [0]: normal symbol `memcpy' [GLIBC_2.14]
</code></pre>
<h2 id="dynamic-linking-x86_64"><a class="header" href="#dynamic-linking-x86_64">Dynamic Linking (x86_64)</a></h2>
<p>Dynamic linking basically works via one indirect jump. It uses a combination of
function trampolines (<code>.plt</code> section) and a function pointer table (<code>.got.plt</code>
section).
On the first call the trampoline sets up some metadata and then jumps to the
<code>ld.so</code> runtime resolve function, which in turn patches the table with the
correct function pointer.</p>
<pre><code class="language-makrdown">  .plt ....... procedure linkage table, contains function trampolines, usually
               located in code segment (rx permission)
  .got.plt ... global offset table for .plt, holds the function pointer table
</code></pre>
<p>Using <code>radare2</code> we can analyze this in more detail:</p>
<pre><code class="language-makrdown">  [0x00401040]&gt; pd 4 @ section..got.plt
              ;-- section..got.plt:
              ;-- .got.plt:    ; [22] -rw- section size 32 named .got.plt
              ;-- _GLOBAL_OFFSET_TABLE_:
         [0]  0x00404000      .qword 0x0000000000403e10 ; section..dynamic
         [1]  0x00404008      .qword 0x0000000000000000
              ; CODE XREF from section..plt @ +0x6
         [2]  0x00404010      .qword 0x0000000000000000
              ;-- reloc.puts:
              ; CODE XREF from sym.imp.puts @ 0x401030
         [3]  0x00404018      .qword 0x0000000000401036 ; RELOC 64 puts

  [0x00401040]&gt; pd 6 @ section..plt
              ;-- section..plt:
              ;-- .plt:       ; [12] -r-x section size 32 named .plt
          ┌─&gt; 0x00401020      ff35e22f0000   push qword [0x00404008]
          â•Ž   0x00401026      ff25e42f0000   jmp qword [0x00404010]
          â•Ž   0x0040102c      0f1f4000       nop dword [rax]
  ┌ 6: int sym.imp.puts (const char *s);
  â””       â•Ž   0x00401030      ff25e22f0000   jmp qword [reloc.puts]
          â•Ž   0x00401036      6800000000     push 0
          └─&lt; 0x0040103b      e9e0ffffff     jmp sym..plt
</code></pre>
<ul>
<li>At address <code>0x00401030</code> in the <code>.plt</code> section we see the indirect jump for
<code>puts</code> using the function pointer in <code>_GLOBAL_OFFSET_TABLE_[3] (GOT)</code>.</li>
<li><code>GOT[3]</code> initially points to instruction after the <code>puts</code> trampoline
<code>0x00401036</code>.</li>
<li>This pushes the relocation index <code>0</code> and then jumps to the first trampoline
<code>0x00401020</code>.</li>
<li>The first trampoline jumps to <code>GOT[2]</code> which will be filled at program
startup by the <code>ld.so</code> with its resolve function.</li>
<li>The <code>ld.so</code> resolve function fixes the relocation referenced by the
relocation index pushed by the <code>puts</code> trampoline.</li>
<li>The relocation entry at index <code>0</code> tells the resolve function which symbol to
search for and where to put the function pointer:
<pre><code class="language-makrdown">  &gt; readelf -r &lt;main&gt;
    &gt;&gt; Relocation section '.rela.plt' at offset 0x4b8 contains 1 entry:
    &gt;&gt;   Offset          Info           Type           Sym. Value    Sym. Name + Addend
    &gt;&gt; 000000404018  000200000007 R_X86_64_JUMP_SLO 0000000000000000 puts@GLIBC_2.2.5 + 0
</code></pre>
As we can see the offset from relocation at index <code>0</code> points to <code>GOT[3]</code>.</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="elf-symbol-versioning"><a class="header" href="#elf-symbol-versioning">ELF Symbol Versioning</a></h1>
<p>The <a href="https://refspecs.linuxbase.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/symversion.html">ELF symbol versioning</a> mechanism allows to attach version
information to symbols.
This can be used to express symbol version requirements or to provide certain
symbols multiple times in the same ELF file with different versions (eg for
backwards compatibility).</p>
<p>The <code>libpthread.so</code> library is an example which provides the
<code>pthread_cond_wait</code> symbol multiple times but in different versions.
With readelf the version of the symbol can be seen after the <code>@</code>.</p>
<pre><code class="language-bash">&gt; readelf -W --dyn-syms /lib/libpthread.so

Symbol table '.dynsym' contains 342 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
   ...
   141: 0000f080   696 FUNC    GLOBAL DEFAULT   16 pthread_cond_wait@@GLIBC_2.3.2
   142: 00010000   111 FUNC    GLOBAL DEFAULT   16 pthread_cond_wait@GLIBC_2.2.5
</code></pre>
<p>The <code>@@</code> denotes the <strong>default symbol version</strong> which will be used during
static linking against the library.
The following dump shows that the <code>tmp</code> program linked against <code>lpthread</code> will
depend on the symbol version <code>GLIBC_2.3.2</code>, which is the default version.</p>
<pre><code class="language-bash">&gt; echo &quot;#include &lt;pthread.h&gt;
        int main() {
          return pthread_cond_wait(0,0);
        }&quot; | gcc -o tmp -xc - -lpthread;
  readelf -W --dyn-syms tmp | grep pthread_cond_wait;

Symbol table '.dynsym' contains 7 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
   ...
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_cond_wait@GLIBC_2.3.2 (2)
</code></pre>
<blockquote>
<p>Only <strong>one</strong> symbol can be annotated as the <code>@@</code> default version.</p>
</blockquote>
<p>Using the <code>--version-info</code> flag with readelf, more details on the symbol
version info compiled into the <code>tmp</code> ELF file can be obtained.</p>
<ul>
<li>The <code>.gnu.version</code> section contains the version definition for each symbol in
the <code>.dynsym</code> section. <code>pthread_cond_wait</code> is at index <code>2</code> in the <code>.dynsym</code>
section, the corresponding symbol version is at index <code>2</code> in the
<code>.gnu.version</code> section.</li>
<li>The <code>.gnu.version_r</code> section contains symbol version requirements per shared
library dependency (<code>DT_NEEDED</code> dynamic entry).</li>
</ul>
<pre><code class="language-bash">&gt; readelf -W --version-info --dyn-syms tmp

Symbol table '.dynsym' contains 7 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     2: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_cond_wait@GLIBC_2.3.2 (2)
     3: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.2.5 (3)
     4: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
     5: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_registerTMCloneTable
     6: 0000000000000000     0 FUNC    WEAK   DEFAULT  UND __cxa_finalize@GLIBC_2.2.5 (3)

Version symbols section '.gnu.version' contains 7 entries:
 Addr: 0x0000000000000534  Offset: 0x000534  Link: 6 (.dynsym)
  000:   0 (*local*)       0 (*local*)       2 (GLIBC_2.3.2)   3 (GLIBC_2.2.5)
  004:   0 (*local*)       0 (*local*)       3 (GLIBC_2.2.5)

Version needs section '.gnu.version_r' contains 2 entries:
 Addr: 0x0000000000000548  Offset: 0x000548  Link: 7 (.dynstr)
  000000: Version: 1  File: libc.so.6  Cnt: 1
  0x0010:   Name: GLIBC_2.2.5  Flags: none  Version: 3
  0x0020: Version: 1  File: libpthread.so.0  Cnt: 1
  0x0030:   Name: GLIBC_2.3.2  Flags: none  Version: 2
</code></pre>
<p>The gnu dynamic linker allows to inspect the version processing during runtime
by setting the <code>LD_DEBUG</code> environment variable accordingly.</p>
<pre><code class="language-text"># version: Display version dependencies.
&gt; LD_DEBUG=versions ./tmp
    717904: checking for version `GLIBC_2.2.5' in file /usr/lib/libc.so.6 [0] required by file ./tmp [0]
    717904: checking for version `GLIBC_2.3.2' in file /usr/lib/libpthread.so.0 [0] required by file ./tmp [0]
    ...

#  symbols : Display symbol table processing.
#  bindings: Display information about symbol binding.
&gt; LD_DEBUG=symbols,bindings ./tmp
    ...
    718123: symbol=pthread_cond_wait;  lookup in file=./tmp [0]
    718123: symbol=pthread_cond_wait;  lookup in file=/usr/lib/libpthread.so.0 [0]
    718123: binding file ./tmp [0] to /usr/lib/libpthread.so.0 [0]: normal symbol `pthread_cond_wait' [GLIBC_2.3.2]
</code></pre>
<h2 id="example-version-script"><a class="header" href="#example-version-script">Example: version script</a></h2>
<p>The following shows an example C++ library <code>libfoo</code> which provides the same
symbol multiple times but in different versions.</p>
<pre><code class="language-cpp">// file: libfoo.cc
#include&lt;stdio.h&gt;

// Bind function symbols to version nodes.
//
// ..@       -&gt; Is the unversioned symbol.
// ..@@..    -&gt; Is the default symbol.

__asm__(&quot;.symver func_v0,func@&quot;);
__asm__(&quot;.symver func_v1,func@LIB_V1&quot;);
__asm__(&quot;.symver func_v2,func@@LIB_V2&quot;);

extern &quot;C&quot; {
    void func_v0() { puts(&quot;func_v0&quot;); }
    void func_v1() { puts(&quot;func_v1&quot;); }
    void func_v2() { puts(&quot;func_v2&quot;); }
}

__asm__(&quot;.symver _Z11func_cpp_v1i,_Z8func_cppi@LIB_V1&quot;);
__asm__(&quot;.symver _Z11func_cpp_v2i,_Z8func_cppi@@LIB_V2&quot;);

void func_cpp_v1(int) { puts(&quot;func_cpp_v1&quot;); }
void func_cpp_v2(int) { puts(&quot;func_cpp_v2&quot;); }

void func_cpp(int) { puts(&quot;func_cpp_v2&quot;); }
</code></pre>
<p>Version script for <code>libfoo</code> which defines which symbols for which versions are
exported from the ELF file.</p>
<pre><code class="language-ld"># file: libfoo.ver
LIB_V1 {
    global:
        func;
        extern &quot;C++&quot; {
            &quot;func_cpp(int)&quot;;
        };
    local:
        *;
};

LIB_V2 {
    global:
        func;
        extern &quot;C++&quot; {
            &quot;func_cpp(int)&quot;;
        };
} LIB_V1;
</code></pre>
<blockquote>
<p>The <strong>local:</strong> section in <code>LIB_V1</code> is a catch all, that matches any symbol
not explicitly specified, and defines that the symbol is local and therefore
not exported from the ELF file.</p>
</blockquote>
<p>The library <code>libfoo</code> can be linked with the version definitions in <code>libfoo.ver</code>
by passing the version script to the linker with the <code>--version-script</code> flag.</p>
<pre><code class="language-bash">&gt; g++ -shared -fPIC -o libfoo.so libfoo.cc -Wl,--version-script=libfoo.ver
&gt; readelf -W --dyn-syms libfoo.so | c++filt

Symbol table '.dynsym' contains 14 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
   ...
     6: 0000000000000000     0 OBJECT  GLOBAL DEFAULT  ABS LIB_V1
     7: 000000000000114b    29 FUNC    GLOBAL DEFAULT   13 func_cpp(int)@LIB_V1
     8: 0000000000001168    29 FUNC    GLOBAL DEFAULT   13 func_cpp(int)@@LIB_V2
     9: 0000000000001185    29 FUNC    GLOBAL DEFAULT   13 func_cpp(int)@@LIB_V1
    10: 0000000000000000     0 OBJECT  GLOBAL DEFAULT  ABS LIB_V2
    11: 0000000000001109    22 FUNC    GLOBAL DEFAULT   13 func
    12: 000000000000111f    22 FUNC    GLOBAL DEFAULT   13 func@LIB_V1
    13: 0000000000001135    22 FUNC    GLOBAL DEFAULT   13 func@@LIB_V2
</code></pre>
<p>The following program demonstrates how to make use of the different versions:</p>
<pre><code class="language-cpp">// file: main.cc
#include &lt;dlfcn.h&gt;
#include &lt;assert.h&gt;

// Links against default symbol in the lib.so.
extern &quot;C&quot; void func();

int main() {
    // Call the default version.
    func();

#ifdef _GNU_SOURCE
    typedef void (*fnptr)();

    // Unversioned lookup.
    fnptr fn_v0 = (fnptr)dlsym(RTLD_DEFAULT, &quot;func&quot;);
    // Version lookup.
    fnptr fn_v1 = (fnptr)dlvsym(RTLD_DEFAULT, &quot;func&quot;, &quot;LIB_V1&quot;);
    fnptr fn_v2 = (fnptr)dlvsym(RTLD_DEFAULT, &quot;func&quot;, &quot;LIB_V2&quot;);

    assert(fn_v0 != 0);
    assert(fn_v1 != 0);
    assert(fn_v2 != 0);

    fn_v0();
    fn_v1();
    fn_v2();
#endif

    return 0;
}
</code></pre>
<p>Compiling and running results in:</p>
<pre><code class="language-bash">&gt; g++ -o main main.cc -ldl ./libfoo.so &amp;&amp; ./main
func_v2
func_v0
func_v1
func_v2
</code></pre>
<h2 id="references-2"><a class="header" href="#references-2">References</a></h2>
<ul>
<li><a href="https://akkadia.org/drepper/symbol-versioning">ELF Symbol Versioning</a></li>
<li><a href="https://sourceware.org/binutils/docs/ld/VERSION.html">Binutils ld: Symbol Versioning</a></li>
<li><a href="https://refspecs.linuxbase.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/symversion.html">LSB: Symbol Versioning</a></li>
<li><a href="https://akkadia.org/drepper/dsohowto.pdf">How To Write Shared Libraries</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="python"><a class="header" href="#python">python</a></h1>
<h2 id="decorator-run"><a class="header" href="#decorator-run">Decorator [<a href="https://www.online-python.com/IDdiE0gpYU">run</a>]</a></h2>
<p>Some decorator examples with type annotation.</p>
<pre><code class="language-python">from typing import Callable

def log(f: Callable[[int], None]) -&gt; Callable[[int], None]:
    def inner(x: int):
        print(f&quot;log::inner f={f.__name__} x={x}&quot;)
        f(x)
    return inner

@log
def some_fn(x: int):
    print(f&quot;some_fn x={x}&quot;)


def log_tag(tag: str) -&gt; Callable[[Callable[[int], None]], Callable[[int], None]]:
    def decorator(f: Callable[[int], None]) -&gt; Callable[[int], None]:
        def inner(x: int):
            print(f&quot;log_tag::inner f={f.__name__} tag={tag} x={x}&quot;)
            f(x)
        return inner
    return decorator

@log_tag(&quot;some_tag&quot;)
def some_fn2(x: int):
    print(f&quot;some_fn2 x={x}&quot;)
</code></pre>
<h2 id="walrus-operator-run"><a class="header" href="#walrus-operator-run">Walrus operator [<a href="https://www.online-python.com/9T12PvmKVy">run</a>]</a></h2>
<p>Walrus operator <code>:=</code> added since <strong>python 3.8</strong>.</p>
<pre><code class="language-python">from typing import Optional

# Example 1: if let statements

def foo(ret: Optional[int]) -&gt; Optional[int]:
    return ret

if r := foo(None):
    print(f&quot;foo(None) -&gt; {r}&quot;)

if r := foo(1337):
    print(f&quot;foo(1337) -&gt; {r}&quot;)

# Example 2: while let statements

toks = iter(['a', 'b', 'c'])
while tok := next(toks, None):
    print(f&quot;{tok}&quot;)

# Example 3: list comprehension

print([tok for t in [&quot;  a&quot;, &quot;  &quot;, &quot; b &quot;] if (tok := t.strip())])
</code></pre>
<h2 id="unittest-run"><a class="header" href="#unittest-run"><a href="https://docs.python.org/3/library/unittest.html">Unittest</a> [<a href="https://www.online-python.com/2fit4UcbzI">run</a>]</a></h2>
<p>Run unittests directly from the command line as <br />
<code>python3 -m unittest -v test</code></p>
<p>Optionally pass <code>-k &lt;patter&gt;</code> to only run subset of tests.</p>
<pre><code class="language-python"># file: test.py

import unittest

class MyTest(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass
    # Tests need to start with the prefix 'test'.
    def test_foo(self):
        self.assertEqual(1 + 2, 3)
    def test_bar(self):
        with self.assertRaises(IndexError):
            list()[0]
</code></pre>
<h2 id="doctest-run"><a class="header" href="#doctest-run"><a href="https://docs.python.org/3/library/doctest.html">Doctest</a> [<a href="https://www.online-python.com/LZst51UNIH">run</a>]</a></h2>
<p>Run doctests directly from the command line as <br />
<code>python -m doctest -v test.py</code></p>
<pre><code class="language-python"># file: test.py

def sum(a: int, b: int) -&gt; int:
    &quot;&quot;&quot;Sum a and b.

    &gt;&gt;&gt; sum(1, 2)
    3

    &gt;&gt;&gt; sum(10, 20)
    30
    &quot;&quot;&quot;
    return a + b
</code></pre>
<h2 id="timeit"><a class="header" href="#timeit"><a href="https://docs.python.org/3/library/timeit.html">timeit</a></a></h2>
<p>Micro benchmarking.</p>
<pre><code class="language-bash">python -m timeit '[x.strip() for x in [&quot;a &quot;, &quot; b&quot;]]'
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="linux"><a class="header" href="#linux">Linux</a></h1>
<ul>
<li><a href="linux/./systemd.html">systemd</a></li>
<li><a href="linux/./coredump.html">coredump</a></li>
<li><a href="linux/./ptrace_scope.html">ptrace_scope</a></li>
<li><a href="linux/./cryptsetup.html">cryptsetup</a></li>
<li><a href="linux/./swap.html">swap</a></li>
<li><a href="linux/./input.html">input</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="systemd"><a class="header" href="#systemd">systemd</a></h1>
<h2 id="systemctl"><a class="header" href="#systemctl">systemctl</a></h2>
<p>Inspect units:</p>
<pre><code class="language-text">systemctl [opts] [cmd]
[opts]
    --user

[cmd]
    list-units &lt;pattern&gt;    List units in memory

    status &lt;unit&gt;           Show runtime status of unit

    start &lt;unit&gt;            Start a unit
    stop &lt;unit&gt;             Stop a unit
    restart &lt;unit&gt;          Restart a unit
    reload &lt;unit&gt;           Reload a unit

    enable &lt;unit&gt;           Enable a unit (persistent)
    disable &lt;unit&gt;          Disable a unit

    cat &lt;unit&gt;      Print unit file
    show &lt;unit&gt;     Show properties of unit
</code></pre>
<h3 id="example-trivial-user-unit"><a class="header" href="#example-trivial-user-unit">Example: Trivial user unit</a></h3>
<pre><code class="language-bash"># Generate unit
mkdir -p ~/.config/systemd/user
echo '[Unit]
Description=Test logger

[Service]
Type=oneshot
ExecStart=logger &quot;Hello from test unit&quot;' &gt; ~/.config/systemd/user/test.service

# Run unit
systemctl --user start test

# See log message
journalctl --user -u test -n 5
</code></pre>
<h2 id="journalctl"><a class="header" href="#journalctl">journalctl</a></h2>
<p>Inspect journal logs:</p>
<pre><code class="language-text">journalctl [opts] [matches]
    --user          Current user journal (system by default)
    -u &lt;unit&gt;       Show logs for specified &lt;unit&gt;
    -n &lt;lines&gt;      Show only last &lt;lines&gt;
    -f              Follow journal
    -g &lt;pattern&gt;    Grep for &lt;pattern&gt;
</code></pre>
<p>Cleanup:</p>
<pre><code class="language-text">journalctl [opts]
    --disk-usage            Show current disk usage
    --vacuum-size=&lt;size&gt;    Reduce journal log to &lt;size&gt; (K/M/G)
</code></pre>
<h2 id="references-3"><a class="header" href="#references-3">References</a></h2>
<ul>
<li><a href="https://www.man7.org/linux/man-pages/man5/systemd.unit.5.html">man systemd.unit(5)</a></li>
<li><a href="https://www.man7.org/linux/man-pages/man5/systemd.service.5.html">man systemd.service(5)</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="core5"><a class="header" href="#core5">core(5)</a></h1>
<p>There are multiple requirements that must be satisfied that <code>coredumps</code> are
being generated, a full list can be found in <a href="https://man7.org/linux/man-pages/man5/core.5.html">core(5)</a>.</p>
<p>An important one is to configure the soft resource limit <code>RLMIT_CORE</code>
(typically as unlimited during debugging).
In a typical bash/zsh this can be done as</p>
<pre><code class="language-bash">ulimit -Sc unlimited
</code></pre>
<h2 id="naming-of-coredump-files"><a class="header" href="#naming-of-coredump-files">Naming of coredump files</a></h2>
<p>There are two important kernel configs to control the naming:</p>
<pre><code class="language-config">/proc/sys/kernel/core_pattern
    &lt;pattern&gt;    =&gt; Specifies a name pattern for the coredump file. This can
                    include certain FORMAT specifier.
    |&lt;cmdline&gt;   =&gt; Coredump is pipe through stdin to the user space process
                    specified by the cmdline, this can also contain FORMAT specifier.

  FORMAT specifier (full list, see core(5)):
    %E      Pathname of the executable ('/' replaced by '!').
    %p      PID of the dumping process in its pid namespace.
    %P      PID of the dumping process in the initial pid namespace.
    %u      Real UID of dumping process.
    %s      Signal number causing the dump.


/proc/sys/kernel/core_uses_pid
    1  =&gt; Append &quot;.&lt;pid&gt;&quot; suffic to the coredump file name
          (pid of the dumping process).
    0  =&gt; Do not append the suffix.
</code></pre>
<h2 id="control-which-segments-are-dumped"><a class="header" href="#control-which-segments-are-dumped">Control which segments are dumped</a></h2>
<p>Each process has a coredump filter defined in <code>/proc/&lt;pid&gt;/coredump_filter</code>
which specifies which memory segments are being dumped.
Filters are preseved across <code>fork/exec</code> calls and hence child processes inherit
the parents filters.</p>
<p>The filter is a bitmask where <code>1</code> indicates to dump the given type.</p>
<pre><code>From core(5):
  bit 0  Dump anonymous private mappings.
  bit 1  Dump anonymous shared mappings.
  bit 2  Dump file-backed private mappings.
  bit 3  Dump file-backed shared mappings.
  bit 4  Dump ELF headers.
  bit 5  Dump private huge pages.
  bit 6  Dump shared huge pages.
  bit 7  Dump private DAX pages.
  bit 8  Dump shared DAX pages.

Default filter 0x33.
</code></pre>
<h1 id="some-examples-out-there"><a class="header" href="#some-examples-out-there">Some examples out there</a></h1>
<h2 id="coredumpctl-systemd"><a class="header" href="#coredumpctl-systemd">coredumpctl (systemd)</a></h2>
<pre><code class="language-bash"># List available coredumps.
coredumpctl list
    TIME                             PID  UID  GID SIG     COREFILE EXE               SIZE
    ...
    Fri 2022-03-11 12:10:48 CET     6363 1000 1000 SIGSEGV present  /usr/bin/sleep   18.1K

# Get detailed info on specific coredump.
coredumpctl info 6363

# Debug specific coredump.
coredumpctl debug 6363

# Dump specific coredump to file.
coredumpctl dump 6363 -o &lt;file&gt;
</code></pre>
<h2 id="apport-ubuntu"><a class="header" href="#apport-ubuntu">apport (ubuntu)</a></h2>
<p>Known crash report locations:</p>
<ul>
<li><code>/var/crash</code></li>
</ul>
<p>To get to the raw coredump, crash reports can be unpacked as:</p>
<pre><code class="language-bash">apport-unpack &lt;crash_repot&gt; &lt;dest_dir&gt;
</code></pre>
<p>The coredump resides under <code>&lt;dest_dir&gt;/CoreDump</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="ptrace_scope"><a class="header" href="#ptrace_scope">ptrace_scope</a></h1>
<p>In case the kernel was compiled with the <code>yama</code> security module
(<code>CONFIG_SECURITY_YAMA</code>), tracing processes with <code>ptrace(2)</code> can be restricted.</p>
<pre><code class="language-config">/proc/sys/kernel/yama/ptrace_scope
    0 =&gt; No restrictions.
    1 =&gt; Restricted attach, only the following can attach
            - A process in the parent hierarchy.
            - A process with CAP_SYS_PTRACE.
            - A process with the PID that the tracee allowed by via
              PR_SET_PTRACER.
    2 =&gt; Only processes with CAP_SYS_PTRACE in the user namespace of the tracee
         can attach.
    3 =&gt; No tracing allowed.
</code></pre>
<p>Further details in <a href="https://man7.org/linux/man-pages/man2/ptrace.2.html"><code>ptrace(2)</code></a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="cryptsetup8"><a class="header" href="#cryptsetup8"><a href="https://www.man7.org/linux/man-pages/man8/cryptsetup.8.html">cryptsetup(8)</a></a></h1>
<pre><code class="language-text">cryptsetup &lt;action&gt; [opts] &lt;action args&gt;

action:
    open &lt;dev&gt; &lt;name&gt; --type &lt;type&gt;    Open (decrypt) &lt;dev&gt; and map with &lt;name&gt;.
                                       Mapped as /dev/mapper/&lt;name&gt;.
                                       Type: {luks,plain,tcrypt,bitlk}
    close &lt;name&gt;                       Close existing mapping &lt;name&gt;.
    status &lt;name&gt;                      Print status for mapping &lt;name&gt;.

    luksFormat &lt;dev&gt;                   Create new LUKS partition and set initial passphrase.
                                       (Keyslot 0)
    luksAddKey &lt;dev&gt;                   Add a new passphrase.
    luksRemoveKey &lt;dev&gt;                Remove existing passphrase.
    luksChangeKey &lt;dev&gt;                Change existing passphrase.
    lusDump &lt;dev&gt;                      Dump LUKS header for device.
</code></pre>
<h2 id="example-create-luks-encrypted-disk"><a class="header" href="#example-create-luks-encrypted-disk">Example: Create <code>LUKS</code> encrypted disk.</a></h2>
<p>For this example we use a file as backing storage and set it up as
<a href="https://man7.org/linux/man-pages/man4/loop.4.html">loop(4)</a> device. The loop device can be replaced by any block
device file.</p>
<blockquote>
<p>Optional: Overwrite existing data on disk.<br />
<code>sudo dd if=/dev/urandom of=/dev/sdX bs=1M</code></p>
</blockquote>
<p>First create the backing file and setup the loop device.</p>
<pre><code class="language-sh"># Create 100MB file.
dd if=/dev/zero of=blkfile bs=1M count=100

# Attach file to first free (-f) loop device
sudo losetup -f ./blkfile
# List loop devices.
sudo losetup -l
# NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE              DIO LOG-SEC
# /dev/loop0         0      0         0  0 /home/johannst/blkfile   0     512
</code></pre>
<p>Create a new LUKS partition and format new filesystem.</p>
<pre><code class="language-sh"># Initialize LUKS partition and set initial passphrase.
sudo cryptsetup luksFormat /dev/loop0

file blkfile
# blkfile: LUKS encrypted file, ver 2 [, , sha256] UUID: 8...

# Open (decrypt) the LUKS device, it will be mapped under /dev/mapper/loop0.
sudo cryptsetup open --type luks /dev/loop0 loop0

# Format partition with new filesystem.
sudo mkfs.vfat /dev/mapper/loop0

lsblk -f
# NAME        FSTYPE    FSVER LABEL  UUID  FSAVAIL FSUSE% MOUNTPOINTS
# loop0       crypto_LU 2            8...
# └─loop0     vfat      FAT16        D...    83.8M     0% /home/johannst/mnt

# Close (re-encrypt) LUKS device.
sudo cryptsetup close loop0
</code></pre>
<h2 id="example-using-an-existing-luks-device"><a class="header" href="#example-using-an-existing-luks-device">Example: Using an existing LUKS device.</a></h2>
<pre><code class="language-sh"># Open (decrypt) the LUKS device, it will be mapped under /dev/mapper/loop0.
sudo cryptsetup open --type luks /dev/loop0 loop0

# Mount filesystem.
sudo mount /dev/mapper/loop0 &lt;mntpoint&gt;

# Use disk ...

# Unmount filesystem.
sudo umount &lt;mntpoint&gt;

# Close (re-encrypt) LUKS device.
sudo cryptsetup close loop0
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="swap"><a class="header" href="#swap">swap</a></h1>
<h2 id="list-active-swap-areas"><a class="header" href="#list-active-swap-areas">List active swap areas</a></h2>
<pre><code class="language-sh"># procfs
cat /proc/swaps

# cli tool
swapon --show
</code></pre>
<h2 id="manual-swapfile-setup"><a class="header" href="#manual-swapfile-setup">Manual swapfile setup</a></h2>
<pre><code class="language-sh"># One time:
#   Create and initialize swapfile.
#   mkswap will initialize swap area over full filesize by default.
sudo dd if=/dev/zero of=/swapfile bs=1G count=1
mkswap /swapfile

# Enable swap file (until next reboot).
swapon /swapfile

# Persistent setup of swap file.
echo &quot;/swapfile none swap sw 0 0&quot; | sudo tee -a /etc/fstab

# Disable swap file (until next reboot).
swapoff /swapfile
</code></pre>
<blockquote>
<p>Recommended file permissions <code>0600</code> and file owner <code>uid=0 (root)</code>.</p>
</blockquote>
<h2 id="using-dphys-swapfile-service"><a class="header" href="#using-dphys-swapfile-service">Using <code>dphys-swapfile</code> service.</a></h2>
<p>Dynamically computes size of swap file based on installed RAM.</p>
<pre><code class="language-sh"># Setup and enable swap based on /etc/dphys-swapfile.
dphys-swapfile setup
dphys-swapfile swapon

# Disable swap on configured file.
dphys-swapfile swapoff
</code></pre>
<blockquote>
<p>Usually comes with a script to be automatically run at system startup and shutdown.
For example as <code>systemd</code> service:</p>
<pre><code>systemctl status dphys-swapfile
</code></pre>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="linux-input"><a class="header" href="#linux-input">Linux input</a></h1>
<p>Some notes on using <code>/dev/input/*</code> device driver files.</p>
<h2 id="mousex--mice"><a class="header" href="#mousex--mice">mouseX / mice</a></h2>
<p>These device files are created by the [mousedev] driver.</p>
<ul>
<li><code>/dev/input/mouseX</code> represents the input stream for a <em>SINGLE</em> mouse device.</li>
<li><code>/dev/input/mice</code> represents the merged input stream for <em>ALL</em> mouse devices.</li>
</ul>
<p>The data stream consists of <code>3 bytes</code> per <code>event</code>. An event is encoded as <code>(BTN, X, Y)</code>.</p>
<ul>
<li><code>BTN</code> button pressed</li>
<li><code>X</code> movement in x-direction <code>-1 -&gt; left</code> and <code>1 -&gt; right</code></li>
<li><code>Y</code> movement in y-direction <code>-1 -&gt; down</code> and <code>1 -&gt; up</code></li>
</ul>
<p>The raw data stream can be inspected as follows.</p>
<pre><code class="language-bash">sudo cat /dev/input/mice | od -tx1 -w3 -v
</code></pre>
<h2 id="eventx"><a class="header" href="#eventx">eventX</a></h2>
<p>These device files are created by the [evdev] driver.</p>
<ul>
<li><code>/dev/input/eventX</code> represents the generic input event interface a <em>SINGLE</em> input deivece.</li>
</ul>
<p>Input events are encoded as given by the <code>input_event</code> struct below. Reading
from the <code>eventX</code> device file will always yield whole number of input events.</p>
<pre><code class="language-c">struct input_event {
    struct timeval time;
    unsigned short type;
    unsigned short code;
    unsigned int value;
};
</code></pre>
<p>On most 64bit machines the raw data stream can be inspected as follows.</p>
<pre><code class="language-bash">sudo cat /dev/input/event4 | od -tx1 -w24 -v
</code></pre>
<h2 id="identifyin-device-files"><a class="header" href="#identifyin-device-files">Identifyin device files.</a></h2>
<p>To find out which device file is assigned to which input device the following
file <code>/proc/bus/input/devices</code> in the proc filesystem can be consulted.</p>
<p>This yields entries as follows and shows which <code>Handlers</code> are assigned to which
<code>Name</code>.</p>
<pre><code>I: Bus=0018 Vendor=04f3 Product=0033 Version=0000
N: Name=&quot;Elan Touchpad&quot;
...
H: Handlers=event15 mouse0
...
</code></pre>
<h2 id="example-toying-with-devinputeventx"><a class="header" href="#example-toying-with-devinputeventx">Example: Toying with <code>/dev/input/eventX</code></a></h2>
<p>Once compiled, the example should be run as <code>sudo ./event /dev/input/eventX</code>.</p>
<pre><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;assert.h&gt;
#include &lt;unistd.h&gt;
#include &lt;time.h&gt;

#include &lt;sys/time.h&gt;
#include &lt;linux/input-event-codes.h&gt;

struct input_event {
    struct timeval time;
    unsigned short type;
    unsigned short code;
    unsigned int value;
};

const char* type(unsigned short t) {
    static char buf[32];
    const char* fmt = &quot;0x%x&quot;;
    switch (t) {
#define FMT(TYPE) case TYPE: fmt = #TYPE&quot;(0x%x)&quot;; break
        FMT(EV_SYN);
        FMT(EV_KEY);
        FMT(EV_REL);
        FMT(EV_ABS);
#undef FMT
    }
    snprintf(buf, sizeof(buf), fmt, t);
    return buf;
}

const char* code(unsigned short c) {
    static char buf[32];
    const char* fmt = &quot;0x%x&quot;;
    switch (c) {
#define FMT(CODE) case CODE: fmt = #CODE&quot;(0x%x)&quot;; break
        FMT(BTN_LEFT);
        FMT(BTN_RIGHT);
        FMT(BTN_MIDDLE);
        FMT(REL_X);
        FMT(REL_Y);
#undef FMT
    }
    snprintf(buf, sizeof(buf), fmt, c);
    return buf;
}

const char* timefmt(const struct timeval* t) {
    assert(t);
    struct tm* lt = localtime(&amp;t-&gt;tv_sec); // Returns pointer to static tm object.
    static char buf[64];
    strftime(buf, sizeof(buf), &quot;%H:%M:%S&quot;, lt);
    return buf;
}

int main(int argc, char* argv[]) {
    assert(argc == 2);

    int fd = open(argv[1], O_RDONLY);
    assert(fd != -1);

    struct input_event inp;
    while (1) {
        int ret = read(fd, &amp;inp, sizeof(inp));
        assert(ret == sizeof(inp));
        printf(&quot;time: %s type: %s code: %s value: 0x%x\n&quot;,
               timefmt(&amp;inp.time), type(inp.type), code(inp.code), inp.value);
    }
}
</code></pre>
<p>[mousedev]: TODO /home/johannst/dev/linux/drivers/input/mousedev.c
[evdev]: TODO /home/johannst/dev/linux/drivers/input/evdev.c</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="network-1"><a class="header" href="#network-1">Network</a></h1>
<ul>
<li><a href="network/./tcpdump.html">tcpdump</a></li>
<li><a href="network/./firewall-cmd.html">firewall-cmd</a></li>
<li><a href="network/./nftables.html">nftables</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="tcpdump1"><a class="header" href="#tcpdump1">tcpdump(1)</a></h1>
<h1 id="cli-3"><a class="header" href="#cli-3">CLI</a></h1>
<pre><code class="language-markdown">tcpdump [opts] -i &lt;if&gt; [&lt;filter&gt;]
    -n              Don't covert host/port names.
    -w &lt;file|-&gt;     Write pcap trace to file or stdout (-).
    -r &lt;file&gt;       Read &amp; parse pcap file.
</code></pre>
<p>Some useful filters.</p>
<pre><code class="language-markdown">src &lt;ip&gt;                Filter for source IP.
dst &lt;ip&gt;                Filter for destination IP.
host &lt;ip&gt;               Filter for IP (src + dst).
net &lt;ip&gt;/&lt;range&gt;        Filter traffic on subnet.
[src/dst] port &lt;port&gt;   Filter for port (optionally src/dst).
tcp/udp/icmp            Filter for protocol.
</code></pre>
<blockquote>
<p>Use <code>and/or/not</code> and <code>()</code> to build filter expressions.</p>
</blockquote>
<h1 id="examples-7"><a class="header" href="#examples-7">Examples</a></h1>
<h2 id="capture-packets-from-remote-host"><a class="header" href="#capture-packets-from-remote-host">Capture packets from remote host</a></h2>
<pre><code class="language-makrdown"># -k: Start capturing immediately.
ssh &lt;host&gt; tcpdump -i any -w - | sudo wireshark -k -i -
</code></pre>
<blockquote>
<p>The <code>any</code> interface is a special keyword to capture traffic on all interfaces.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="firewall-cmd1"><a class="header" href="#firewall-cmd1">firewall-cmd(1)</a></h1>
<p>Command line interface to the <a href="https://firewalld.org/documentation/man-pages/firewalld.html">firewalld(1)</a> daemon.</p>
<h2 id="list-current-status-of-the-firewall"><a class="header" href="#list-current-status-of-the-firewall">List current status of the firewall</a></h2>
<pre><code class="language-sh"># List all services and ports for all zones.
firewall-cmd --list-all
# List all services.
firewall-cmd --list-services
# List all ports.
firewall-cmd --list-ports
</code></pre>
<blockquote>
<p>Add <code>--zone &lt;ZONE&gt;</code> to limit output to a given <code>ZONE</code>. Use <code>--get-zones</code> to
see all available zones.</p>
</blockquote>
<h2 id="add-entries"><a class="header" href="#add-entries">Add entries</a></h2>
<pre><code class="language-sh"># Add a service to the firewall, use `--get-services` to list all available
# service names.
firewall-cmd --add-service &lt;SERVICE&gt;
# Add a specific port.
firewall-cmd --add-port 8000/tcp
# Add a rich rule (eg port forwarding, dnat).
firewall-cmd --add-rich-rule 'rule family=&quot;ipv4&quot; forward-port port=&quot;80&quot; protocol=&quot;tcp&quot; to-port=&quot;8080&quot;'
</code></pre>
<h2 id="remove-entries"><a class="header" href="#remove-entries">Remove entries</a></h2>
<pre><code class="language-sh"># Remove service.
firewall-cmd --remove-service &lt;SERVICE&gt;
# Remove port.
firewall-cmd --remove-port 8000/tcp
# Remove rich rule.
firewall-cmd --remove-rich-rule 'rule family=&quot;ipv4&quot; forward-port port=&quot;80&quot; protocol=&quot;tcp&quot; to-port=&quot;8080&quot;'
</code></pre>
<h2 id="references-4"><a class="header" href="#references-4">References</a></h2>
<ul>
<li>man <a href="https://firewalld.org/documentation/man-pages/firewall-cmd.html">firewall-cmd(1)</a></li>
<li>man <a href="https://firewalld.org/documentation/man-pages/firewalld.html">firewalld(1)</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="nftables"><a class="header" href="#nftables">nftables</a></h1>
<p><a href="https://nftables.org/projects/nftables/index.html">Nftables</a> is a stateful Linux firewall which uses the
<a href="https://nftables.org">netfilter</a> kernel hooks.
It is used for stateless, stateful packet filtering and all sorts of NAT.</p>
<p>Nftables is the successor to <a href="https://nftables.org/projects/iptables/index.html">iptables</a>.</p>
<p>In nftables, <code>rules</code> are organized with <code>chains</code> and <code>tables</code>.</p>
<ul>
<li><code>chain</code>: Orders <code>rules</code>. Chains exist in two kinds:
<ul>
<li><code>base chain</code>: Entry point from netfilter hooks (network stack).</li>
<li><code>regular chain</code>: Can be used as jump target to group rules for better organization.</li>
</ul>
</li>
<li><code>table</code>: Groups chains together. Tables are defined by a <code>name</code> and an
<code>address family</code> (eg <code>inet</code>, <code>ip</code>, <code>ip6</code>, ..).</li>
</ul>
<h2 id="ruleset"><a class="header" href="#ruleset">Ruleset</a></h2>
<pre><code class="language-bash">nft list ruleset        # List all tables/chains/rules (whole ruleset).
nft flush ruleset       # Clear whole ruleset.
</code></pre>
<h2 id="examples-save-rules-to-files-and-re-apply"><a class="header" href="#examples-save-rules-to-files-and-re-apply">Examples: Save rules to files and re-apply</a></h2>
<pre><code class="language-bash">nft list ruleset &gt; nft.rules
nft flush ruleset
nft -f nft.rules
</code></pre>
<h2 id="example-fully-trace-evaluation-of-nftables-rules"><a class="header" href="#example-fully-trace-evaluation-of-nftables-rules">Example: Fully trace evaluation of nftables rules</a></h2>
<pre><code class="language-text">table ip traceall {
    chain filter_prerouting {
        # Install chain with higher priority as the RAW standard priority.
        type filter hook prerouting priority raw - 50; policy accept;
        # Trace each and every packet (very verbose).
        #meta nftrace set 1;
        # Trace packet to port 80/81/8081 from localhost.
        tcp dport { 80, 81, 8081 } ip saddr 127.0.0.1 meta nftrace set 1;
    }
}
</code></pre>
<p>Use <code>nft monitor trace</code> to get trace output on tty.</p>
<h2 id="example-ipv4-port-forwarding"><a class="header" href="#example-ipv4-port-forwarding">Example: IPv4 port forwarding</a></h2>
<pre><code class="language-text">table ip fwd {
    chain nat_preroute {
        # Register this chain to the PREROUTE:NAT hook (stateful packet tracking via conntrack).
        type nat hook prerouting priority dstnat + 10 ; policy accept;
        meta nfproto ipv4 tcp dport 81 redirect to :8081
    }
}
</code></pre>
<h2 id="example-base-vs-regular-chain"><a class="header" href="#example-base-vs-regular-chain">Example: Base vs regular chain</a></h2>
<pre><code class="language-text"># Table named 'playground' handling 'ip' (ipv4) address family.
table ip playground {
    # Base chain.
    chain filter_input_base {
        # Register this chain to the INPUT:FILTER hook in the netfilter package flow.
        # Specify a prioirty relative to the inbuilt 'filter' priority (smaller
        # number means higher priority).
        # Set the default policy to ACCEPT, to let every packet pass by default.
        type filter hook input priority filter - 10; policy accept;

        # Create a rule for tcp packets arriving on either port 8000 or 8100.
        tcp dport { 8000, 8100 } jump input_reg_log;
        # Create a rule for tcp packets arriving on port 8200.
        tcp dport 8200 jump input_reg_log_all;
    }

    # Regular chain.
    chain input_reg_log {
        # Log every packet traversing this chain.
        # Message lands in the kernel ring buffer.
        log;
    }

    # Regular chain.
    chain input_reg_log_all {
        # Log every packet with all flags traversing this chain.
        log flags all;
    }
}
</code></pre>
<pre><code class="language-bash"># Load the nf rules.
sudo nft -f playground.rules
# Create test servers.
nc -lk 0.0.0.0 8000
nc -lk 0.0.0.0 8100
nc -lk 0.0.0.0 8200
# See the nftables logging in the kernel ring buffer.
sudo dmesg -w
# Make some client connections.
nc localhost 8000
nc localhost 8200
</code></pre>
<h2 id="mental-model-for-netfilter-packet-flow"><a class="header" href="#mental-model-for-netfilter-packet-flow">Mental model for netfilter packet flow</a></h2>
<p><img src="network/assets/nf_pkt_flow.png" alt="nf_pkt_flow.png" /></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="web"><a class="header" href="#web">Web</a></h1>
<ul>
<li><a href="web/./html.html">html</a></li>
<li><a href="web/./chartjs.html">chartjs</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="html"><a class="header" href="#html">html</a></h1>
<h2 id="collapsible-element"><a class="header" href="#collapsible-element">Collapsible element</a></h2>
<p><a href="web/src/details.html">Rendered html</a></p>
<pre><code class="language-html">&lt;details&gt;
  &lt;summary&gt;Some text goes here&lt;/summary&gt;
  ... some more text goes here.
&lt;/details&gt;
</code></pre>
<blockquote>
<p>With the <code>open</code> attribute <code>&lt;details open&gt;</code> the details are unfolded by default.</p>
</blockquote>
<h1 id="minimal-2-column-layout"><a class="header" href="#minimal-2-column-layout">Minimal 2 column layout</a></h1>
<p><a href="web/src/grid-2col.html">Rendered html</a></p>
<pre><code class="language-html">&lt;style&gt;
.grid-2col {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 1em
}
.col1 {
  grid-column-start: 1;
  background-color: red;
  padding-left: 1em;
}
.col2 {
  grid-column-start: 2;
  background-color: green;
  padding-left: 1em;
}
&lt;/style&gt;
&lt;div class=&quot;grid-2col&quot;&gt;
  &lt;div class=&quot;col1&quot;&gt;
    &lt;p&gt;Some text in the first column.&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class=&quot;col2&quot;&gt;
    &lt;p&gt;Some text in the second column.&lt;/p&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<h1 id="minimal-grid-area"><a class="header" href="#minimal-grid-area">Minimal grid area</a></h1>
<p><a href="web/src/grid-area.html">Rendered html</a></p>
<pre><code class="language-html">&lt;style&gt;
.page-grid {
  display: grid;
  grid-template-columns: 1fr 2fr;
  grid-template-areas:
      &quot;h h&quot;
      &quot;s m&quot;
      &quot;f f&quot;;
  gap: 1em;
}
.gh {
  grid-area: h;
  background-color: orange;
}
.gs {
  grid-area: s;
  background-color: green;
}
.gm {
  grid-area: m;
  background-color: gray;
}
.gf {
  grid-area: f;
  background-color: yellow;
}
.nav-items {
  display: flex;                  /* flexbox model =&gt; flexible layout on row */
  justify-content: space-around;  /* align flex boxes horizontally with space around */
  align-items: center;            /* center flex items vertically */
  list-style: none;
}
p {
  margin: 1em;
}
&lt;/style&gt;
&lt;div class=&quot;page-grid&quot;&gt;
  &lt;div class=&quot;gh&quot;&gt;
      &lt;ul class=&quot;nav-items&quot;&gt;
          &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;&quot;&gt;aa&lt;/a&gt;&lt;/li&gt;
          &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;&quot;&gt;bb&lt;/a&gt;&lt;/li&gt;
          &lt;li class=&quot;nav-item&quot;&gt;&lt;a href=&quot;&quot;&gt;cc&lt;/a&gt;&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/div&gt;
  &lt;div class=&quot;gs&quot;&gt;
    &lt;p&gt;Some text in the second column.&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class=&quot;gm&quot;&gt;
    &lt;p&gt;Some text in the second column.&lt;/p&gt;
  &lt;/div&gt;
  &lt;div class=&quot;gf&quot;&gt;
    &lt;p&gt;Some text in the second column.&lt;/p&gt;
  &lt;/div&gt;
&lt;/div&gt;

</code></pre>
<h1 id="minimal-tabs"><a class="header" href="#minimal-tabs">Minimal tabs</a></h1>
<p><a href="web/src/tabs.html">Rendered html</a></p>
<pre><code class="language-html">&lt;script&gt;
const showTab = (E, T) =&gt; {
    const TABS = Array.from(document.getElementsByClassName(&quot;content&quot;));
    TABS.forEach(T =&gt; {
        T.style.display = &quot;none&quot;;
    });

    document.getElementById(T).style.display = &quot;block&quot;;
};

window.onload = () =&gt; {
    document.getElementById(&quot;bTab1&quot;).onclick = (E) =&gt; {
        showTab(E, &quot;tTab1&quot;);
    };
    document.getElementById(&quot;bTab2&quot;).onclick = (E) =&gt; {
        showTab(E, &quot;tTab2&quot;);
    };
}
&lt;/script&gt;

&lt;button type=&quot;button&quot; id=&quot;bTab1&quot;&gt;Tab1&lt;/button&gt;
&lt;button type=&quot;button&quot; id=&quot;bTab2&quot;&gt;Tab2&lt;/button&gt;

&lt;div id=&quot;tTab1&quot; class=&quot;content&quot; style=&quot;display: block;&quot;&gt;
    &lt;p&gt;Some content goes here ...&lt;/p&gt;
&lt;/div&gt;

&lt;div id=&quot;tTab2&quot; class=&quot;content&quot; style=&quot;display: none;&quot;&gt;
    &lt;p&gt;... and there.&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="chartjs"><a class="header" href="#chartjs">Chart.js</a></h1>
<h2 id="minimal-example-with-external-tooltips"><a class="header" href="#minimal-example-with-external-tooltips">Minimal example with <em>external</em> tooltips</a></h2>
<p><a href="web/src/chartjs-ext-tooltip.html">Rendered html</a></p>
<pre><code class="language-html">&lt;canvas id=&quot;myChart&quot; style=&quot;margin:5em;&quot;&gt;&lt;/canvas&gt;

&lt;script&gt;
const get_or_create_tooltip = (id) =&gt; {
  if (tooltip = document.getElementById(id)) {
    return tooltip;
  } else {
    // -- Create a new Tooltip element.
    const tooltip = document.createElement('div');
    tooltip.id = id;
    document.body.appendChild(tooltip);

    // -- Some minimal styling.
    tooltip.style.background = 'rgba(0, 0, 0, 0.1)';
    tooltip.style.position   = 'absolute';
    tooltip.style.transition = 'all .2s ease';

    // -- Add a table element for the tooltip content.
    const table = document.createElement('table');
    tooltip.appendChild(table);

    return tooltip
  }
}

const render_tooltip = (context) =&gt; {
  const {chart, tooltip} = context;

  // -- Get Tooltip element.
  const tooltip_elem = get_or_create_tooltip('myTooltip');

  // -- Get data point values (only one data point).
  const {label: x, formattedValue: y} = tooltip.dataPoints[0];

  // -- Format new tooltip.
  const link = document.createElement('a');
  link.href =  &quot;https://github.com/johannst&quot;;
  link.innerHTML = &quot;X:&quot; + x + &quot; Y:&quot; + y;

  // -- Remove previous child element and add new one.
  const table = tooltip_elem.querySelector('table');
  table.innerHTML = &quot;&quot;; 
  table.appendChild(link);

  // -- Get absolute X/Y position of the top left corner of the canvas.
  const {offsetLeft: canvas_x, offsetTop: canvas_y} = chart.canvas;

  // -- Set position and minimal style for the tooltip.
  tooltip_elem.style.left = canvas_x + tooltip.caretX + 'px';
  tooltip_elem.style.top  = canvas_y + tooltip.caretY + 'px';
  tooltip_elem.style.font = tooltip.options.bodyFont.string;

  // -- Place the tooltip (I) left or (II) right of the data point.
  if (tooltip.xAlign === &quot;right&quot;) {
    tooltip_elem.style.transform = 'translate(-100%, 0)'; // (I)
  } else if (tooltip.xAlign === &quot;left&quot;) {
    tooltip_elem.style.transform = 'translate(0%, 0)';    // (II)
  }
}

// -- Render a chart with some dummy data on the canvas.
const chart = new Chart(
  document.getElementById('myChart'),
  {
    data: {
      datasets: [{
        // -- A single dataset.
        label: 'Just some values',
        type: 'scatter',
        data: [
          {x: 4, y: 4},
          {x: 5, y: 1},
          {x: 7, y: 6},
          {x: 10, y: 8},
          {x: 10, y: 7},
          {x: 10, y: 3},
        ],
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
        borderColor: 'rgb(255, 99, 132)',
      }],
    },
    options: {
      scales: {
        y: {
          beginAtZero: true, // -- Start the Y-Axis at zero instead min(y) of dataset.
        }
      },
      plugins: {
        tooltip: {
          enabled: false, // -- Disable builtin tooltips.
          mode: 'nearest', // -- Get the item that is nearest to the mouse.
          intersect: false, // -- 'mode' is active also when the mouse doesnt intersect with an item on the chart.
          external: render_tooltip, // -- External tooltip handler, allows to create own HTML.
        }
      }
    }
  }
);
&lt;/script&gt;
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="arch"><a class="header" href="#arch">Arch</a></h1>
<ul>
<li><a href="arch/./x86_64.html">x86_64</a></li>
<li><a href="arch/./arm64.html">arm64</a></li>
<li><a href="arch/./armv7.html">armv7</a></li>
<li><a href="arch/./riscv.html">riscv</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="x86_64"><a class="header" href="#x86_64">x86_64</a></h1>
<p>keywords: x86_64, x86, abi</p>
<ul>
<li>64bit synonyms: <code>x86_64</code>, <code>x64</code>, <code>amd64</code>, <code>intel 64</code></li>
<li>32bit synonyms: <code>x86</code>, <code>ia32</code>, <code>i386</code></li>
<li>ISA type: <code>CISC</code></li>
<li>Endianness: <code>little</code></li>
</ul>
<h2 id="registers"><a class="header" href="#registers">Registers</a></h2>
<h3 id="general-purpose-register"><a class="header" href="#general-purpose-register">General purpose register</a></h3>
<pre><code class="language-markdown">bytes
[7:0]      [3:0]   [1:0]   [1]   [0]     desc
----------------------------------------------------------
rax        eax     ax      ah    al      accumulator
rbx        ebx     bx      bh    bl      base register
rcx        ecx     cx      ch    cl      counter
rdx        edx     dx      dh    dl      data register
rsi        esi     si      -     sil     source index
rdi        edi     di      -     dil     destination index
rbp        ebp     bp      -     bpl     base pointer
rsp        esp     sp      -     spl     stack pointer
r8-15      rNd     rNw     -     rNb
</code></pre>
<h3 id="special-register"><a class="header" href="#special-register">Special register</a></h3>
<pre><code class="language-markdown">bytes
[7:0]      [3:0]     [1:0]      desc
---------------------------------------------------
rflags     eflags    flags      flags register
rip        eip       ip         instruction pointer
</code></pre>
<h3 id="flags-register"><a class="header" href="#flags-register">FLAGS register</a></h3>
<pre><code class="language-markdown">rflags
bits    desc                            instr        comment
--------------------------------------------------------------------------------------------------------------
   [21]   ID   identification                        ability to set/clear -&gt; indicates support for CPUID instr
   [18]   AC   alignment check                       alignment exception for PL 3 (user), requires CR0.AM
[13:12] IOPL   io privilege level
   [11]   OF   overflow flag
   [10]   DF   direction flag           cld/std      increment (0) or decrement (1) registers in string operations
    [9]   IF   interrupt enable         cli/sti
    [7]   SF   sign flag
    [6]   ZF   zero flag
    [4]   AF   auxiliary carry flag
    [2]   PF   parity flag
    [0]   CF   carry flag
</code></pre>
<p>Change flag bits with <code>pushf</code> / <code>popf</code> instructions:</p>
<pre><code class="language-x86asm">pushfd                          // push flags (4bytes) onto stack
or dword ptr [esp], (1 &lt;&lt; 18)   // enable AC flag
popfd                           // pop flags (4byte) from stack
</code></pre>
<blockquote>
<p>There is also <code>pushfq</code> / <code>popfq</code> to push and pop all 8 bytes of <code>rflags</code>.</p>
</blockquote>
<h3 id="model-specific-register-msr"><a class="header" href="#model-specific-register-msr">Model Specific Register (MSR)</a></h3>
<pre><code class="language-x86asm">rdmsr     // Read MSR register, effectively does EDX:EAX &lt;- MSR[ECX]
wrmsr     // Write MSR register, effectively does MSR[ECX] &lt;- EDX:EAX
</code></pre>
<h2 id="size-directives"><a class="header" href="#size-directives">Size directives</a></h2>
<p>Explicitly specify size of the operation.</p>
<pre><code class="language-x86asm">mov  byte ptr [rax], 0xff    // save 1 byte(s) at [rax]
mov  word ptr [rax], 0xff    // save 2 byte(s) at [rax]
mov dword ptr [rax], 0xff    // save 4 byte(s) at [rax]
mov qword ptr [rax], 0xff    // save 8 byte(s) at [rax]
</code></pre>
<h2 id="addressing"><a class="header" href="#addressing">Addressing</a></h2>
<pre><code class="language-x86asm">mov qword ptr [rax], rbx         // save val in rbx at [rax]
mov qword ptr [imm], rbx         // save val in rbx at [imm]
mov rax, qword ptr [rbx+4*rcx]   // load val at [rbx+4*rcx] into rax
</code></pre>
<p><code>rip</code> relative addressing:</p>
<pre><code class="language-x86asm">lea rax, [rip+.my_str]       // load addr of .my_str into rax
...
.my_str:
.asciz &quot;Foo&quot;
</code></pre>
<p>Load effective address:</p>
<pre><code class="language-x86asm">mov rax, 2
lea r11, [rax + 3]   // r11 &lt;- 5
</code></pre>
<h2 id="string-instructions"><a class="header" href="#string-instructions">String instructions</a></h2>
<p>The operand size of a string instruction is defined by the instruction suffix
<code>b | w | d | q</code>.</p>
<p>Source and destination registers are modified according to the <code>direction flag (DF)</code> in the <code>flags</code> register</p>
<ul>
<li><code>DF=0</code> increment src/dest registers</li>
<li><code>DF=1</code> decrement src/dest registers</li>
</ul>
<p>Following explanation assumes <code>byte</code> operands with <code>DF=0</code>:</p>
<pre><code class="language-x86asm">movsb   // move data from string to string
        // ES:[DI] &lt;- DS:[SI]
        // DI &lt;- DI + 1
        // SI &lt;- SI + 1

lodsb   // load string
        // AL &lt;- DS:[SI]
        // SI &lt;- SI + 1

stosb   // store string
        // ES:[DI] &lt;- AL
        // DI &lt;- DI + 1

cmpsb   // compare string operands
        // DS:[SI] - ES:[DI]    ; set status flag (eg ZF)
        // SI &lt;- SI + 1
        // DI &lt;- DI + 1

scasb   // scan string
        // AL - ES:[DI]         ; set status flag (eg ZF)
        // DI &lt;- DI + 1
</code></pre>
<p>String operations can be repeated:</p>
<pre><code class="language-x86asm">rep     // repeat until rcx = 0
repz    // repeat until rcx = 0 or while ZF = 0
repnz   // repeat until rcx = 0 or while ZF = 1
</code></pre>
<h3 id="example-simple-memset"><a class="header" href="#example-simple-memset">Example: Simple <code>memset</code></a></h3>
<pre><code class="language-x86asm">// memset (dest, 0xaa /* char */, 0x10 /* len */)

lea di, [dest]
mov al, 0xaa
mov cx, 0x10
rep stosb
</code></pre>
<h2 id="sysv-x86_64-abi"><a class="header" href="#sysv-x86_64-abi"><a href="https://www.uclibc.org/docs/psABI-x86_64.pdf">SysV x86_64 ABI</a></a></h2>
<h3 id="passing-arguments-to-functions"><a class="header" href="#passing-arguments-to-functions">Passing arguments to functions</a></h3>
<ul>
<li>Integer/Pointer arguments
<pre><code class="language-markdown">reg     arg
-----------
rdi       1
rsi       2
rdx       3
rcx       4
r8        5
r9        6
</code></pre>
</li>
<li>Floating point arguments
<pre><code class="language-markdown">reg     arg
-----------
xmm0      1
  ..     ..
xmm7      8
</code></pre>
</li>
<li>Additional arguments are passed on the stack. Arguments are pushed
right-to-left (RTL), meaning next arguments are closer to current <code>rsp</code>.</li>
</ul>
<h3 id="return-values-from-functions"><a class="header" href="#return-values-from-functions">Return values from functions</a></h3>
<ul>
<li>Integer/Pointer return values
<pre><code class="language-markdown">reg          size
-----------------
rax        64 bit
rax+rdx   128 bit
</code></pre>
</li>
<li>Floating point return values:
<pre><code class="language-markdown">reg            size
-------------------
xmm0         64 bit
xmm0+xmm1   128 bit
</code></pre>
</li>
</ul>
<h3 id="caller-saved-registers"><a class="header" href="#caller-saved-registers">Caller saved registers</a></h3>
<p>Caller must save these registers if they should be preserved across function
calls.</p>
<ul>
<li><code>rax</code></li>
<li><code>rcx</code></li>
<li><code>rdx</code></li>
<li><code>rsi</code></li>
<li><code>rdi</code></li>
<li><code>rsp</code></li>
<li><code>r8</code> - <code>r11</code></li>
</ul>
<h3 id="callee-saved-registers"><a class="header" href="#callee-saved-registers">Callee saved registers</a></h3>
<p>Caller can expect these registers to be preserved across function calls. Callee
must must save these registers in case they are used.</p>
<ul>
<li><code>rbx</code></li>
<li><code>rbp</code></li>
<li><code>r12</code> – <code>r15</code></li>
</ul>
<h3 id="stack"><a class="header" href="#stack">Stack</a></h3>
<ul>
<li>grows downwards</li>
<li>frames aligned on 16 byte boundary
<pre><code class="language-text">Hi ADDR
 |                +------------+
 |                | prev frame |
 |                +------------+ &lt;--- 16 byte aligned (X &amp; ~0xf)
 |       [rbp+8]  | saved RIP  |
 |       [rbp]    | saved RBP  |
 |       [rbp-8]  | func stack |
 |                | ...        |
 v                +------------+
Lo ADDR
</code></pre>
</li>
</ul>
<h3 id="function-prologue--epilogue"><a class="header" href="#function-prologue--epilogue">Function prologue &amp; epilogue</a></h3>
<ul>
<li>prologue
<pre><code class="language-x86asm">push rbp        // save caller base pointer
mov rbp, rsp    // save caller stack pointer
</code></pre>
</li>
<li>epilogue
<pre><code class="language-x86asm">mov rsp, rbp    // restore caller stack pointer
pop rbp         // restore caller base pointer
</code></pre>
<blockquote>
<p>Equivalent to <code>leave</code> instruction.</p>
</blockquote>
</li>
</ul>
<h2 id="asm-skeleton"><a class="header" href="#asm-skeleton">ASM skeleton</a></h2>
<p>Small assembler skeleton, ready to use with following properties:</p>
<ul>
<li>use raw Linux syscalls (<code>man 2 syscall</code> for ABI)</li>
<li>no <code>C runtime (crt)</code></li>
<li>gnu assembler <a href="https://sourceware.org/binutils/docs/as"><code>gas</code></a></li>
<li>intel syntax</li>
</ul>
<pre><code class="language-x86asm"># file: greet.s

    .intel_syntax noprefix

    .section .text, &quot;ax&quot;, @progbits
    .global _start
_start:
    mov rdi, 1                      # fd
    lea rsi, [rip + greeting]       # buf
    mov rdx, [rip + greeting_len]   # count
    mov rax, 1                      # write(2) syscall nr
    syscall

    mov rdi, 0                      # exit code
    mov rax, 60                     # exit(2) syscall nr
    syscall

    .section .rdonly, &quot;a&quot;, @progbits
greeting:
    .asciz &quot;Hi ASM-World!\n&quot;
greeting_len:
    .int .-greeting
</code></pre>
<blockquote>
<p>Syscall numbers are defined in <code>/usr/include/asm/unistd.h</code>.</p>
</blockquote>
<p>To compile and run:</p>
<pre><code class="language-bash">&gt; gcc -o greet greet.s -nostartfiles -nostdlib &amp;&amp; ./greet
Hi ASM-World!
</code></pre>
<h2 id="references-5"><a class="header" href="#references-5">References</a></h2>
<ul>
<li><a href="https://www.uclibc.org/docs/psABI-x86_64.pdf">SystemV AMD64 ABI</a></li>
<li><a href="https://www.amd.com/system/files/TechDocs/24592.pdf">AMD64 Vol1: Application Programming</a></li>
<li><a href="https://www.amd.com/system/files/TechDocs/24593.pdf">AMD64 Vol2: System Programming</a></li>
<li><a href="https://www.amd.com/system/files/TechDocs/24594.pdf">AMD64 Vol3: General-Purpose &amp; System Instructions</a></li>
<li><a href="https://cs.brown.edu/courses/cs033/docs/guides/x64_cheatsheet.pdf">X86_64 Cheat-Sheet</a></li>
<li><a href="https://software.intel.com/content/www/us/en/develop/download/intel-64-and-ia-32-architectures-software-developers-manual-volume-1-basic-architecture.html">Intel 64 Vol1: Basic Architecture</a></li>
<li><a href="https://software.intel.com/content/www/us/en/develop/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-2a-2b-2c-and-2d-instruction-set-reference-a-z.html">Intel 64 Vol2: Instruction Set Reference</a></li>
<li><a href="https://software.intel.com/content/www/us/en/develop/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-3a-3b-3c-and-3d-system-programming-guide.html">Intel 64 Vol3: System Programming Guide</a></li>
<li><a href="https://sourceware.org/binutils/docs/as">GNU Assembler</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops">GNU Assembler Directives</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/i386_002dDependent.html">GNU Assembler <code>x86_64</code> dependent features</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="arm64"><a class="header" href="#arm64">arm64</a></h1>
<p>keywords: arm64, aarch64, abi</p>
<ul>
<li>64bit synonyms: <code>arm64</code>, <code>aarch64</code></li>
<li>ISA type: <code>RISC</code></li>
<li>Endianness: <code>little</code>, <code>big</code></li>
</ul>
<h2 id="registers-1"><a class="header" href="#registers-1">Registers</a></h2>
<h3 id="general-purpose-registers"><a class="header" href="#general-purpose-registers">General purpose registers</a></h3>
<pre><code class="language-markdown">bytes
[7:0]     [3:0]     desc
---------------------------------------------
x0-x28    w0-w28    general purpose registers
x29       w29       frame pointer (FP)
x30       w30       link register (LR)
sp        wsp       stack pointer (SP)
pc                  program counter (PC)
xzr       wzr       zero register
</code></pre>
<blockquote>
<p>Write to <code>wN</code> register clears upper 32bit.</p>
</blockquote>
<h3 id="special-registers-per-el"><a class="header" href="#special-registers-per-el">Special registers per EL</a></h3>
<pre><code class="language-markdown">bytes
[7:0]       desc
---------------------------------------------
sp_el0      stack pointer EL0

sp_el1      stack pointer EL1
elr_el1     exception link register EL1
spsr_el1    saved process status register EL1

sp_el2      stack pointer EL2
elr_el2     exception link register EL2
spsr_el2    saved process status register EL2

sp_el3      stack pointer EL3
elr_el3     exception link register EL3
spsr_el3    saved process status register EL3
</code></pre>
<h2 id="instructions-cheatsheet"><a class="header" href="#instructions-cheatsheet">Instructions cheatsheet</a></h2>
<h3 id="accessing-system-registers"><a class="header" href="#accessing-system-registers">Accessing system registers</a></h3>
<p>Reading from system registers:</p>
<pre><code class="language-armasm">mrs x0, vbar_el1      // move vbar_el1 into x0
</code></pre>
<p>Writing to system registers:</p>
<pre><code class="language-armasm">msr vbar_el1, x0      // move x0 into vbar_el1
</code></pre>
<h3 id="control-flow-1"><a class="header" href="#control-flow-1">Control Flow</a></h3>
<pre><code class="language-armasm">b &lt;offset&gt;    // relative forward/back branch
br &lt;Xn&gt;       // absolute branch to address in register Xn

// branch &amp; link, store return address in X30 (LR)
bl &lt;offset&gt;   // relative forward/back branch
blr &lt;Xn&gt;      // absolute branch to address in register Xn

ret {Xn}      // return to address in X30, or Xn if supplied
</code></pre>
<h2 id="addressing-1"><a class="header" href="#addressing-1">Addressing</a></h2>
<h3 id="offset"><a class="header" href="#offset">Offset</a></h3>
<pre><code class="language-armasm">ldr x0, [x1]                // x0 = [x1]
ldr x0, [x1, 8]             // x0 = [x1 + 8]
ldr x0, [x1, x2, lsl #3]    // x0 = [x1 + (x2&lt;&lt;3)]
ldr x0, [x1, w2, stxw]      // x0 = [x1 + sign_ext(w2)]
ldr x0, [x1, w2, stxw #3]   // x0 = [x1 + (sign_ext(w2)&lt;&lt;3)]
</code></pre>
<blockquote>
<p>Shift amount can either be <code>0</code> or <code>log2(access_size_bytes)</code>. Eg for 8byte
access it can either be <code>{0, 3}</code>.</p>
</blockquote>
<h3 id="index"><a class="header" href="#index">Index</a></h3>
<pre><code class="language-armasm">ldr x0, [x1, 8]!    // pre-inc : x1+=8; x0 = [x1]
ldr x0, [x1], 8     // post-inc: x0 = [x1]; x1+=8
</code></pre>
<h3 id="pair-access"><a class="header" href="#pair-access">Pair access</a></h3>
<pre><code class="language-armasm">ldp x1, x2, [x0]    // x1 = [x0]; x2 = [x0 + 8]
stp x1, x2, [x0]    // [x0] = x1; [x0 + 8] = x2
</code></pre>
<h2 id="procedure-call-standard-arm64-aapcs64"><a class="header" href="#procedure-call-standard-arm64-aapcs64">Procedure Call Standard ARM64 (<a href="https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst"><code>aapcs64</code></a>)</a></h2>
<h3 id="passing-arguments-to-functions-1"><a class="header" href="#passing-arguments-to-functions-1">Passing arguments to functions</a></h3>
<ul>
<li>Integer/Pointer arguments
<pre><code class="language-markdown">reg     arg
-----------
x0        1
..       ..
x7        8
</code></pre>
</li>
<li>Additional arguments are passed on the stack. Arguments are pushed
<code>right-to-left (RTL)</code>, meaning next arguments are closer to current <code>sp</code>.
<pre><code class="language-markdown">void take(..., int a9, int a10);
                   |       |   | ... |       Hi
                   |       +--&gt;| a10 |       |
                   +----------&gt;| a9  | &lt;-SP  |
                               +-----+       v
                               | ... |       Lo
</code></pre>
</li>
</ul>
<h3 id="return-values-from-functions-1"><a class="header" href="#return-values-from-functions-1">Return values from functions</a></h3>
<ul>
<li>Integer/Pointer return values
<pre><code class="language-markdown">reg          size
-----------------
x0         64 bit
</code></pre>
</li>
</ul>
<h3 id="callee-saved-registers-1"><a class="header" href="#callee-saved-registers-1">Callee saved registers</a></h3>
<ul>
<li><code>x19</code> - <code>x28</code></li>
<li><code>SP</code></li>
</ul>
<h3 id="stack-1"><a class="header" href="#stack-1">Stack</a></h3>
<ul>
<li>full descending
<ul>
<li>full: <code>sp</code> points to the last used location (valid item)</li>
<li>descending: stack grows downwards</li>
</ul>
</li>
<li><code>sp</code> must be 16byte aligned when used to access memory for r/w</li>
<li><code>sp</code> must be 16byte aligned on public interface interfaces</li>
</ul>
<h3 id="frame-chain"><a class="header" href="#frame-chain">Frame chain</a></h3>
<ul>
<li>linked list of stack-frames</li>
<li>each frame links to the frame of its caller by a <code>frame record</code>
<ul>
<li>a frame record is described as a <code>(FP,LR)</code> pair</li>
</ul>
</li>
<li><code>x29 (FP)</code> must point to the frame record of the current stack-frame
<pre><code class="language-markdown">      +------+                   Hi
      |   0  |     frame0        |
   +-&gt;|   0  |                   |
   |  |  ... |                   |
   |  +------+                   |
   |  |  LR  |     frame1        |
   +--|  FP  |&lt;-+                |
      | ...  |  |                |
      +------+  |                |
      |  LR  |  |  current       |
x29 -&gt;|  FP  |--+  frame         v
      | ...  |                   Lo
</code></pre>
</li>
<li>end of the frame chain is indicated by following frame record <code>(0,-)</code></li>
<li>location of the frame record in the stack frame is not specified</li>
</ul>
<h3 id="function-prologue--epilogue-1"><a class="header" href="#function-prologue--epilogue-1">Function prologue &amp; epilogue</a></h3>
<ul>
<li>prologue
<pre><code class="language-armasm">sub sp, sp, 16
stp x29, x30, [sp]      // [sp] = x29; [sp + 8] = x30
mov x29, sp             // FP points to frame record
</code></pre>
</li>
<li>epilogue
<pre><code class="language-armasm">ldp x29, x30, [sp]      // x29 = [sp]; x30 = [sp + 8]
add sp, sp, 16
ret
</code></pre>
</li>
</ul>
<h2 id="asm-skeleton-1"><a class="header" href="#asm-skeleton-1">ASM skeleton</a></h2>
<p>Small assembler skeleton, ready to use with following properties:</p>
<ul>
<li>use raw Linux syscalls (<code>man 2 syscall</code> for ABI)</li>
<li>no <code>C runtime (crt)</code></li>
<li>gnu assembler <a href="https://sourceware.org/binutils/docs/as"><code>gas</code></a></li>
</ul>
<pre><code class="language-armasm">// file: greet.S

#include &lt;asm/unistd.h&gt;      // syscall NRs

    .arch armv8-a

    .section .text, &quot;ax&quot;, @progbits
    .balign 4                // align code on 4byte boundary
    .global _start
_start:
    mov x0, 2                // fd
    ldr x1, =greeting        // buf
    ldr x2, =greeting_len    // &amp;len
    ldr x2, [x2]             // len
    mov w8, __NR_write       // write(2) syscall
    svc 0

    mov x0, 0                // exit code
    mov w8, __NR_exit        // exit(2) syscall
    svc 0

    .balign 8                // align data on 8byte boundary
    .section .rodata, &quot;a&quot;, @progbits
greeting:
    .asciz &quot;Hi ASM-World!\n&quot;
greeting_len:
    .int .-greeting
</code></pre>
<blockquote>
<p>man gcc: <code>file.S</code> assembler code that must be preprocessed.</p>
</blockquote>
<p>To cross-compile and run:</p>
<pre><code class="language-bash">&gt; aarch64-linux-gnu-g++ -o greet greet.S -nostartfiles -nostdlib          \
    -Wl,--dynamic-linker=/usr/aarch64-linux-gnu/lib/ld-linux-aarch64.so.1 \
  &amp;&amp; qemu-aarch64 ./greet
Hi ASM-World!
</code></pre>
<blockquote>
<p>Cross-compiling on <code>Ubuntu 20.04 (x86_64)</code>, paths might differ on other
distributions. Explicitly specifying the dynamic linker should not be
required when compiling natively on arm64.</p>
</blockquote>
<h2 id="references-6"><a class="header" href="#references-6">References</a></h2>
<ul>
<li><a href="https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst">Procedure Call Standard ARM64</a></li>
<li><a href="https://developer.arm.com/documentation/den0024/latest">ARMv8-A Programmer's Guide</a></li>
<li><a href="https://developer.arm.com/documentation/ddi0487/latest">ARMv8-A Architecture Reference Manual</a></li>
<li><a href="https://developer.arm.com/documentation/dai0527/latest">AppNote: ARMv8 Bare-metal boot code</a></li>
<li><a href="https://sourceware.org/binutils/docs/as">GNU Assembler</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops">GNU Assembler Directives</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/AArch64_002dDependent.html">GNU Assembler <code>AArch64</code> dependent features</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="armv7a"><a class="header" href="#armv7a">armv7a</a></h1>
<p>keywords: arm, armv7, abi</p>
<ul>
<li>ISA type: <code>RISC</code></li>
<li>Endianness: <code>little</code>, <code>big</code></li>
</ul>
<h2 id="registers-2"><a class="header" href="#registers-2">Registers</a></h2>
<h3 id="general-purpose-registers-1"><a class="header" href="#general-purpose-registers-1">General purpose registers</a></h3>
<pre><code class="language-markdown">bytes
[3:0]     alt     desc
---------------------------------------------
r0-r12            general purpose registers
r11       fp
r13       sp      stack pointer
r14       lr      link register
r15       pc      program counter
</code></pre>
<h3 id="special-registers"><a class="header" href="#special-registers">Special registers</a></h3>
<pre><code class="language-markdown">bytes
[3:0]             desc
---------------------------------------------
cpsr              current program status register
</code></pre>
<h3 id="cpsr-register"><a class="header" href="#cpsr-register">CPSR register</a></h3>
<pre><code class="language-markdown">cpsr
bits  desc
-----------------------------
 [31]  N negative flag
 [30]  Z zero flag
 [29]  C carry flag
 [28]  V overflow flag
 [27]  Q cummulative saturation (sticky)
  [9]  E load/store endianness
  [8]  A disable asynchronous aborts
  [7]  I disable IRQ
  [6]  F disable FIQ
  [5]  T indicate Thumb state
[4:0]  M process mode (USR, FIQ, IRQ, SVC, ABT, UND, SYS)
</code></pre>
<h2 id="instructions-cheatsheet-1"><a class="header" href="#instructions-cheatsheet-1">Instructions cheatsheet</a></h2>
<h3 id="accessing-system-registers-1"><a class="header" href="#accessing-system-registers-1">Accessing system registers</a></h3>
<p>Reading from system registers:</p>
<pre><code class="language-armasm">mrs r0, cpsr      // move cpsr into r0
</code></pre>
<p>Writing to system registers:</p>
<pre><code class="language-armasm">msr cpsr, r0      // move r0 into cpsr
</code></pre>
<h3 id="control-flow-2"><a class="header" href="#control-flow-2">Control Flow</a></h3>
<pre><code class="language-armasm">b &lt;lable&gt;     // relative forward/back branch
bl &lt;lable&gt;    // relative forward/back branch &amp; link return addr in r14 (LR)

// branch &amp; exchange (can change between ARM &amp; Thumb instruction set)
//   bit Rm[0] == 0 -&gt; ARM
//   bit Rm[0] == 1 -&gt; Thumb
bx &lt;Rm&gt;       // absolute branch to address in register Rm
blx &lt;Rm&gt;      // absolute branch to address in register Rm &amp;
              // link return addr in r14 (LR)
</code></pre>
<h3 id="loadstore"><a class="header" href="#loadstore">Load/Store</a></h3>
<p>Different addressing modes.</p>
<pre><code class="language-armasm">ldr r1, [r0]                // r1 = [r0]
ldr r1, [r0, #4]            // r1 = [r0+4]

ldr r1, [r0, #4]!           // pre-inc : r0+=4; r1 = [r0]
ldr r1, [r0], #4            // post-inc: [r0] = r1; r0+=4

ldr r0, [r1, r2, lsl #3]    // r0 = [r1 + (r2&lt;&lt;3)]
</code></pre>
<p>Load/store multiple registers full-descending.</p>
<pre><code class="language-armasm">stmfd r0!, {r1-r2, r5}    // r0-=4; [r0]=r5
                          // r0-=4; [r0]=r2
                          // r0-=4; [r0]=r1
ldmfd r0!, {r1-r2, r5}    // r1=[r0]; r0+=4
                          // r2=[r0]; r0+=4
                          // r5=[r0]; r0+=4
</code></pre>
<blockquote>
<p><code>!</code> is optional but has the effect to update the base pointer register <code>r0</code> here.</p>
</blockquote>
<p>Push/Pop</p>
<pre><code class="language-armasm">push {r0-r2}    // effectively stmfd sp!, {r0-r2}
pop {r0-r2}     // effectively ldmfd sp!, {r0-r2}
</code></pre>
<h2 id="procedure-call-standard-arm-aapcs32"><a class="header" href="#procedure-call-standard-arm-aapcs32">Procedure Call Standard ARM (<a href="https://github.com/ARM-software/abi-aa/blob/master/aapcs32/aapcs32.rst"><code>aapcs32</code></a>)</a></h2>
<h3 id="passing-arguments-to-functions-2"><a class="header" href="#passing-arguments-to-functions-2">Passing arguments to functions</a></h3>
<ul>
<li>integer/pointer arguments
<pre><code class="language-markdown">reg     arg
-----------
r0        1
..       ..
r3        4
</code></pre>
</li>
<li>a double word (64bit) is passed in two consecutive registers (eg <code>r1+r2</code>)</li>
<li>additional arguments are passed on the stack. Arguments are pushed
<code>right-to-left (RTL)</code>, meaning next arguments are closer to current <code>sp</code>.
<pre><code class="language-markdown">void take(..., int a5, int a6);
                   |       |   | ... |       Hi
                   |       +--&gt;| a6  |       |
                   +----------&gt;| a5  | &lt;-SP  |
                               +-----+       v
                               | ... |       Lo
</code></pre>
</li>
</ul>
<h3 id="return-values-from-functions-2"><a class="header" href="#return-values-from-functions-2">Return values from functions</a></h3>
<ul>
<li>integer/pointer return values
<pre><code class="language-markdown">reg          size
-----------------
r0         32 bit
r0+r1      64 bit
</code></pre>
</li>
</ul>
<h3 id="callee-saved-registers-2"><a class="header" href="#callee-saved-registers-2">Callee saved registers</a></h3>
<ul>
<li><code>r4</code> - <code>r11</code></li>
<li><code>sp</code></li>
</ul>
<h3 id="stack-2"><a class="header" href="#stack-2">Stack</a></h3>
<ul>
<li>full descending
<ul>
<li>full: <code>sp</code> points to the last used location (valid item)</li>
<li>descending: stack grows downwards</li>
</ul>
</li>
<li><code>sp</code> must be 4byte aligned (word boundary) at all time</li>
<li><code>sp</code> must be 8byte aligned on public interface interfaces</li>
</ul>
<h3 id="frame-chain-1"><a class="header" href="#frame-chain-1">Frame chain</a></h3>
<ul>
<li>not strictly required by each platform</li>
<li>linked list of stack-frames</li>
<li>each frame links to the frame of its caller by a <code>frame record</code>
<ul>
<li>a frame record is described as a <code>(FP,LR)</code> pair (2x32bit)</li>
</ul>
</li>
<li><code>r11 (FP)</code> must point to the frame record of the current stack-frame
<pre><code class="language-markdown">      +------+                   Hi
      |   0  |     frame0        |
   +-&gt;|   0  |                   |
   |  |  ... |                   |
   |  +------+                   |
   |  |  LR  |     frame1        |
   +--|  FP  |&lt;-+                |
      | ...  |  |                |
      +------+  |                |
      |  LR  |  |  current       |
r11 -&gt;|  FP  |--+  frame         v
      | ...  |                   Lo
</code></pre>
</li>
<li>end of the frame chain is indicated by following frame record <code>(0,-)</code></li>
<li>location of the frame record in the stack frame is not specified</li>
<li><code>r11</code> is not updated before the new frame record is fully constructed</li>
</ul>
<h3 id="function-prologue--epilogue-2"><a class="header" href="#function-prologue--epilogue-2">Function prologue &amp; epilogue</a></h3>
<ul>
<li>prologue
<pre><code class="language-armasm">push {fp, lr}
mov fp, sp              // FP points to frame record
</code></pre>
</li>
<li>epilogue
<pre><code class="language-armasm">pop {fp, pc}            // pop LR directly into PC
</code></pre>
</li>
</ul>
<h2 id="asm-skeleton-2"><a class="header" href="#asm-skeleton-2">ASM skeleton</a></h2>
<p>Small assembler skeleton, ready to use with following properties:</p>
<ul>
<li>use raw Linux syscalls (<code>man 2 syscall</code> for ABI)</li>
<li>no <code>C runtime (crt)</code></li>
<li>gnu assembler <a href="https://sourceware.org/binutils/docs/as"><code>gas</code></a></li>
</ul>
<pre><code class="language-armasm">// file: greet.S

#include &lt;asm/unistd.h&gt;      // syscall NRs

    .arch armv7-a

    .section .text, &quot;ax&quot;
    .balign 4

    // Emit `arm` instructions, same as `.arm` directive.
    .code 32
    .global _start
_start:
    // Branch with link and exchange instruction set.
    blx _do_greet

    mov r0, #0               // exit code
    mov r7, #__NR_exit       // exit(2) syscall
    swi 0x0

    // Emit `thumb` instructions, same as `.thumb` directive.
    .code 16
    .thumb_func
_do_greet:
    mov r0, #2               // fd
    ldr r1, =greeting        // buf
    ldr r2, =greeting_len    // &amp;len
    ldr r2, [r2]             // len
    mov r7, #__NR_write      // write(2) syscall
    swi 0x0

    // Branch and exchange instruction set.
    bx lr

    .balign 8                // align data on 8byte boundary
    .section .rodata, &quot;a&quot;
greeting:
    .asciz &quot;Hi ASM-World!\n&quot;
greeting_len:
    .int .-greeting
</code></pre>
<blockquote>
<p>man gcc: <code>file.S</code> assembler code that must be preprocessed.</p>
</blockquote>
<p>To cross-compile and run:</p>
<pre><code class="language-bash">&gt; arm-linux-gnueabi-gcc -o greet greet.S -nostartfiles -nostdlib  \
    -Wl,--dynamic-linker=/usr/arm-linux-gnueabi/lib/ld-linux.so.3 \
  &amp;&amp; qemu-arm ./greet
Hi ASM-World!
</code></pre>
<blockquote>
<p>Cross-compiling on <code>Ubuntu 20.04 (x86_64)</code>, paths might differ on other
distributions. Explicitly specifying the dynamic linker should not be
required when compiling natively on arm.</p>
</blockquote>
<h2 id="references-7"><a class="header" href="#references-7">References</a></h2>
<ul>
<li><a href="https://github.com/ARM-software/abi-aa/blob/master/aapcs32/aapcs32.rst">Procedure Call Standard ARM</a></li>
<li><a href="https://developer.arm.com/documentation/den0013/latest">ARMv7-A Programmer's Guide</a></li>
<li><a href="https://developer.arm.com/documentation/ddi0406/latest">ARMv7-A Architecture Reference Manual</a></li>
<li><a href="https://sourceware.org/binutils/docs/as">GNU Assembler</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops">GNU Assembler Directives</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/ARM_002dDependent.html">GNU Assembler <code>ARM</code> dependent features</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="riscv"><a class="header" href="#riscv">riscv</a></h1>
<p>keywords: rv32, rv64</p>
<ul>
<li>ISA type: <code>RISC</code></li>
<li>Endianness: <code>little</code>, <code>big</code></li>
</ul>
<h2 id="registers-3"><a class="header" href="#registers-3">Registers</a></h2>
<ul>
<li>riscv32 =&gt; <code>XLEN=32</code></li>
<li>riscv64 =&gt; <code>XLEN=64</code></li>
</ul>
<h3 id="general-purpose-registers-2"><a class="header" href="#general-purpose-registers-2">General purpose registers</a></h3>
<pre><code class="language-markdown">[XLEN-1:0]     abi name     desc
---------------------------------------------
x0             zero         zero register
x1             ra           return addr
x2             sp           stack ptr
x3             gp           global ptr
x4             tp           thread ptr
x5-x7          t0-t2        temp regs
x8-x9          s0-s1        saved regs
x10-x17        a0-a7        arg regs
x18-x27        s2-s11       saved regs
x28-x31        t3-t6        temp regs
</code></pre>
<h2 id="asm-skeleton-3"><a class="header" href="#asm-skeleton-3">ASM skeleton</a></h2>
<p>Small assembler skeleton, ready to use with following properties:</p>
<ul>
<li>use raw Linux syscalls (<code>man 2 syscall</code> for ABI)</li>
<li>no <code>C runtime (crt)</code></li>
<li>gnu assembler <a href="https://sourceware.org/binutils/docs/as"><code>gas</code></a></li>
</ul>
<pre><code class="language-mipsasm">// file: greet.S

#include &lt;asm/unistd.h&gt;     // syscall NRs

    .section .text, &quot;ax&quot;, @progbits
    .balign 4               // align code on 4byte boundary
    .global _start
_start:
    li a0, 2                // fd
    la a1, greeting         // buf
    ld a2, (greeting_len)   // &amp;len
    li a7, __NR_write       // write(2) syscall
    ecall

    li a0, 42               // exit code
    li a7, __NR_exit        // exit(2) syscall
    ecall

    .balign 8               // align data on 8byte boundary
    .section .rodata, &quot;a&quot;, @progbits
greeting:
    .asciz &quot;Hi ASM-World!\n&quot;
greeting_len:
    .int .-greeting
</code></pre>
<blockquote>
<p>man gcc: <code>file.S</code> assembler code that must be preprocessed.</p>
</blockquote>
<p>To cross-compile and run:</p>
<pre><code class="language-bash">&gt; riscv64-linux-gnu-gcc -o greet greet.S -nostartfiles -nostdlib                \
    -Wl,--dynamic-linker=/usr/riscv64-linux-gnu/lib/ld-linux-riscv64-lp64d.so.1 \
  &amp;&amp; qemu-riscv64 ./greet
Hi ASM-World!
</code></pre>
<blockquote>
<p>Cross-compiling on <code>Ubuntu 20.04 (x86_64)</code>, paths might differ on other
distributions. Explicitly specifying the dynamic linker should not be
required when compiling natively on riscv.</p>
<p>Select dynamic linker according to abi used during compile &amp; link.</p>
</blockquote>
<h2 id="references-8"><a class="header" href="#references-8">References</a></h2>
<ul>
<li><a href="https://sourceware.org/binutils/docs/as">GNU Assembler</a></li>
<li><a href="https://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops">GNU Assembler Directives</a></li>
</ul>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->


                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">

            </nav>

        </div>




        <script>
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>

        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->

        <script>
        window.addEventListener('load', function() {
            window.setTimeout(window.print, 100);
        });
        </script>

    </body>
</html>