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
|
<!--
The FreeBSD Documentation Project
$FreeBSD: doc/en_US.ISO_8859-1/books/developers-handbook/book.sgml,v 1.5 2000/11/06 13:52:26 murray Exp $
-->
<!DOCTYPE BOOK PUBLIC "-//FreeBSD//DTD DocBook V3.1-Based Extension//EN" [
<!ENTITY % bookinfo PUBLIC "-//FreeBSD//ENTITIES DocBook BookInfo Entities//EN">
%bookinfo;
]>
<book>
<bookinfo>
<title>FreeBSD Developers' Handbook</title>
<authorgroup>
<author>
<surname>The FreeBSD Documentation Project</surname>
<affiliation>
<address>
<email>doc@FreeBSD.org</email>
</address>
</affiliation>
</author>
</authorgroup>
<pubdate>August 2000</pubdate>
<copyright>
<year>2000</year>
<holder>The FreeBSD Documentation Project</holder>
</copyright>
&bookinfo.legalnotice;
<abstract>
<para>Welcome to the Developers' Handbook.</para>
</abstract>
</bookinfo>
<part id="introduction">
<title>Introduction</title>
<chapter id="developmentplatform">
<title>Developing on FreeBSD</title>
<para>This will need to discuss FreeBSD as a development
platform, the vision of BSD, architectural overview, layout of
/usr/src, history, etc.</para>
<para>Thank you for considering FreeBSD as your development
platform! We hope it will not let you down.</para>
</chapter>
<chapter id="bsdvision">
<title>The BSD Vision</title>
<para></para>
</chapter>
<chapter id="archoverview">
<title>Architectural Overview</title>
<para></para>
</chapter>
<chapter id="sourcelayout">
<title>The Layout of /usr/src</title>
<para>The complete source code to FreeBSD is available from our
public CVS repository. The source code is normally installed in
<filename class=directory>/usr/src</filename> which contains the
following subdirectories.</para>
<para>
<informaltable frame="none">
<tgroup cols="2">
<thead>
<row>
<entry>Directory</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><filename class=directory>bin/</filename></entry>
<entry>Source for files in
<filename>/bin</filename></entry>
</row>
<row>
<entry><filename class=directory>contrib/</filename></entry>
<entry>Source for files from contribued software.</entry>
</row>
<row>
<entry><filename class=directory>crypto/</filename></entry>
<entry>DES source</entry>
</row>
<row>
<entry><filename class=directory>etc/</filename></entry>
<entry>Source for files in <filename
class=directory>/etc</filename></entry>
</row>
<row>
<entry><filename class=directory>games/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/games</filename></entry>
</row>
<row>
<entry><filename class=directory>gnu/</filename></entry>
<entry>Utilities covered by the GNU Public License</entry>
</row>
<row>
<entry><filename class=directory>include/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/include</filename></entry>
</row>
<row>
<entry><filename
class=directory>kerberosIV/</filename></entry>
<entry>Source for Kerbereros version IV</entry>
</row>
<row>
<entry><filename
class=directory>kerberos5/</filename></entry>
<entry>Source for Kerbereros version 5</entry>
</row>
<row>
<entry><filename class=directory>lib/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/lib</filename></entry>
</row>
<row>
<entry><filename class=directory>libexec/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/libexec</filename></entry>
</row>
<row>
<entry><filename
class=directory>release/</filename></entry>
<entry>Files required to produce a FreeBSD release</entry>
</row>
<row>
<entry><filename class=directory>sbin/</filename></entry>
<entry>Source for files in <filename
class=directory>/sbin</filename></entry>
</row>
<row>
<entry><filename class=directory>secure/</filename></entry>
<entry>FreeSec sources</entry>
</row>
<row>
<entry><filename class=directory>share/</filename></entry>
<entry>Source for files in <filename
class=directory>/sbin</filename></entry>
</row>
<row>
<entry><filename class=directory>sys/</filename></entry>
<entry>Kernel source files</entry>
</row>
<row>
<entry><filename class=directory>tools/</filename></entry>
<entry>Tools used for maintenance and testing of
FreeBSD</entry>
</row>
<row>
<entry><filename
class=directory>usr.bin/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/bin</filename></entry>
</row>
<row>
<entry><filename
class=directory>usr.sbin/</filename></entry>
<entry>Source for files in <filename
class=directory>/usr/sbin</filename></entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</chapter>
</part>
<part id="Basics">
<title>Basics</title>
<chapter id="programming-tools">
<title>Programming Tools</title>
<para><emphasis>This chapter was written by James Raynard.
Modifications for the Developer's Handbook by Murray Stokely.
</emphasis></para>
<sect1><title>Synopsis</title>
<para>This document is an introduction to using some of the
programming tools supplied with FreeBSD, although much of it
will be applicable to many other versions of Unix. It does
<emphasis>not</emphasis> attempt to describe coding in any
detail. Most of the document assumes little or no previous
programming knowledge, although it is hoped that most
programmers will find something of value in it</para>
</sect1>
<sect1><title>Introduction</title>
<para>FreeBSD offers an excellent development environment.
Compilers for C, C++, and Fortran and an assembler come with the
basic system, not to mention a Perl interpreter and classic Unix
tools such as <command>sed</command> and <command>awk</command>.
If that is not enough, there are many more compilers and
interpreters in the Ports collection. FreeBSD is very
compatible with standards such as <acronym>POSIX</acronym> and
<acronym>ANSI</acronym> C, as well with its own BSD heritage, so
it is possible to write applications that will compile and run
with little or no modification on a wide range of
platforms.</para>
<para>However, all this power can be rather overwhelming at
first if you've never written programs on a Unix platform
before. This document aims to help you get up and running,
without getting too deeply into more advanced topics. The
intention is that this document should give you enough of the
basics to be able to make some sense of the
documentation.</para>
<para>Most of the document requires little or no knowledge of
programming, although it does assume a basic competence with
using Unix and a willingness to learn!</para>
</sect1>
<sect1>
<title>Introduction to Programming</title>
<para>A program is a set of instructions that tell the computer
to do various things; sometimes the instruction it has to
perform depends on what happened when it performed a previous
instruction. This section gives an overview of the two main
ways in which you can give these instructions, or
<quote>commands</quote> as they are usually called. One way
uses an <firstterm>interpreter</firstterm>, the other a
<firstterm>compiler</firstterm>. As human languages are too
difficult for a computer to understand in an unambiguous way,
commands are usually written in one or other languages specially
designed for the purpose.</para>
<sect2>
<title>Interpreters</title>
<para>With an interpreter, the language comes as an environment,
where you type in commands at a prompt and the environment
executes them for you. For more complicated programs, you can
type the commands into a file and get the interpreter to load
the file and execute the commands in it. If anything goes
wrong, many interpreters will drop you into a debugger to help
you track down the problem.</para>
<para>The advantage of this is that you can see the results of
your commands immediately, and mistakes can be corrected
readily. The biggest disadvantage comes when you want to
share your programs with someone. They must have the same
interpreter, or you must have some way of giving it to them,
and they need to understand how to use it. Also users may not
appreciate being thrown into a debugger if they press the
wrong key! From a performance point of view, interpreters can
use up a lot of memory, and generally do not generate code as
efficiently as compilers.</para>
<para>In my opinion, interpreted languages are the best way to
start if you have not done any programming before. This kind
of environment is typically found with languages like Lisp,
Smalltalk, Perl and Basic. It could also be argued that the
Unix shell (<command>sh</command>, <command>csh</command>) is itself an
interpreter, and many people do in fact write shell
<quote>scripts</quote> to help with various
<quote>housekeeping</quote> tasks on their machine. Indeed, part
of the original Unix philosophy was to provide lots of small
utility programs that could be linked together in shell
scripts to perform useful tasks.</para>
</sect2>
<sect2>
<title>Interpreters available with FreeBSD</title>
<para>Here is a list of interpreters that are available as
<ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/">FreeBSD
packages</ulink>, with a brief discussion of some of the
more popular interpreted languages.</para>
<para>To get one of these packages, all you need to do is to
click on the hotlink for the package, then run</para>
<screen>&prompt.root; <userinput>pkg_add <replaceable>package name</></userinput>
</screen>
<para>as root. Obviously, you will need to have a fully
functional FreeBSD 2.1.0 or later system for the package to
work!</para>
<variablelist>
<varlistentry>
<term><acronym>BASIC</acronym></term>
<listitem>
<para>Short for Beginner's All-purpose Symbolic
Instruction Code. Developed in the 1950s for teaching
University students to program and provided with every
self-respecting personal computer in the 1980s,
<acronym>BASIC</acronym> has been the first programming
language for many programmers. It's also the foundation
for Visual Basic.</para>
<para>The <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/bwbasic-2.10.tgz">Bywater
Basic Interpreter</ulink> and the <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/pbasic-2.0.tgz">Phil
Cockroft's Basic Interpreter</ulink> (formerly Rabbit
Basic) are available as FreeBSD <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/">FreeBSD
packages</ulink></para>
</listitem>
</varlistentry>
<varlistentry>
<term>Lisp</term>
<listitem>
<para>A language that was developed in the late 1950s as
an alternative to the <quote>number-crunching</quote>
languages that were popular at the time. Instead of
being based on numbers, Lisp is based on lists; in fact
the name is short for <quote>List Processing</quote>.
Very popular in AI (Artificial Intelligence)
circles.</para>
<para>Lisp is an extremely powerful and sophisticated
language, but can be rather large and unwieldy.</para>
<para>FreeBSD has <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/gcl-2.0.tgz">GNU
Common Lisp</ulink> available as a package.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Perl</term>
<listitem>
<para>Very popular with system administrators for writing
scripts; also often used on World Wide Web servers for
writing <acronym>CGI</acronym> scripts.</para>
<para>The latest version (version 5) comes with FreeBSD.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Scheme</term>
<listitem>
<para>A dialect of Lisp that is rather more compact and
cleaner than Common Lisp. Popular in Universities as it
is simple enough to teach to undergraduates as a first
language, while it has a high enough level of
abstraction to be used in research work.</para>
<para>FreeBSD has packages of the <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/elk-3.0.tgz">Elk
Scheme Interpreter</ulink>, the <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/mit-scheme-7.3.tgz">MIT
Scheme Interpreter</ulink> and the <ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/scm-4e1.tgz">SCM
Scheme Interpreter</ulink>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Icon</term>
<listitem>
<para><ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/icon-9.0.tgz">The
Icon Programming Language</ulink>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Logo</term>
<listitem>
<para><ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/ucblogo-3.3.tgz">Brian
Harvey's LOGO Interpreter</ulink>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>Python</term>
<listitem>
<para><ulink
URL="ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/python-1.2">The
Python Object-Oriented Programming
Language</ulink></para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2>
<title>Compilers</title>
<para>Compilers are rather different. First of all, you write
your code in a file (or files) using an editor. You then run
the compiler and see if it accepts your program. If it did
not compile, grit your teeth and go back to the editor; if it
did compile and gave you a program, you can run it either at a
shell command prompt or in a debugger to see if it works
properly.
<footnote>
<para>If you run it in the shell, you may get a core
dump.</para>
</footnote></para>
<para>Obviously, this is not quite as direct as using an
interpreter. However it allows you to do a lot of things
which are very difficult or even impossible with an
interpreter, such as writing code which interacts closely with
the operating system—or even writing your own operating
system! It's also useful if you need to write very efficient
code, as the compiler can take its time and optimise the code,
which would not be acceptable in an interpreter. And
distributing a program written for a compiler is usually more
straightforward than one written for an interpreter—you
can just give them a copy of the executable, assuming they
have the same operating system as you.</para>
<para>Compiled languages include Pascal, C and C++. C and C++
are rather unforgiving languages, and best suited to more
experienced programmers; Pascal, on the other hand, was
designed as an educational language, and is quite a good
language to start with. Unfortunately, FreeBSD doesn't have
any Pascal support, except for a Pascal-to-C converter in the
ports.</para>
<para>As the edit-compile-run-debug cycle is rather tedious when
using separate programs, many commercial compiler makers have
produced Integrated Development Environments
(<acronym>IDE</acronym>s for short). FreeBSD does not have an
<acronym>IDE</acronym> as such; however it is possible to use Emacs
for this purpose. This is discussed in <xref
linkend="emacs">.</para>
</sect2>
</sect1>
<sect1>
<title>Compiling with <command>cc</command></title>
<para>This section deals only with the GNU compiler for C and C++,
since that comes with the base FreeBSD system. It can be
invoked by either <command>cc</command> or <command>gcc</command>. The
details of producing a program with an interpreter vary
considerably between interpreters, and are usually well covered
in the documentation and on-line help for the
interpreter.</para>
<para>Once you've written your masterpiece, the next step is to
convert it into something that will (hopefully!) run on FreeBSD.
This usually involves several steps, each of which is done by a
separate program.</para>
<procedure>
<step>
<para>Pre-process your source code to remove comments and do
other tricks like expanding macros in C.</para>
</step>
<step>
<para>Check the syntax of your code to see if you have obeyed
the rules of the language. If you have not, it will
complain!</para>
</step>
<step>
<para>Convert the source code into assembly
language—this is very close to machine code, but still
understandable by humans. Allegedly.
<footnote>
<para>To be strictly accurate, <command>cc</command> converts the
source code into its own, machine-independent
<firstterm>p-code</firstterm> instead of assembly language at
this stage.</para>
</footnote></para>
</step>
<step>
<para>Convert the assembly language into machine
code—yep, we are talking bits and bytes, ones and
zeros here.</para>
</step>
<step>
<para>Check that you have used things like functions and
global variables in a consistent way. For example, if you
have called a non-existent function, it will
complain.</para>
</step>
<step>
<para>If you are trying to produce an executable from several
source code files, work out how to fit them all
together.</para>
</step>
<step>
<para>Work out how to produce something that the system's
run-time loader will be able to load into memory and
run.</para>
</step>
<step>
<para>Finally, write the executable on the file system.</para>
</step>
</procedure>
<para>The word <firstterm>compiling</firstterm> is often used to refer to
just steps 1 to 4—the others are referred to as
<firstterm>linking</firstterm>. Sometimes step 1 is referred to as
<firstterm>pre-processing</firstterm> and steps 3-4 as
<firstterm>assembling</firstterm>.</para>
<para>Fortunately, almost all this detail is hidden from you, as
<command>cc</command> is a front end that manages calling all these
programs with the right arguments for you; simply typing</para>
<screen>&prompt.user; <userinput>cc foobar.c</>
</screen>
<para>will cause <filename>foobar.c</filename> to be compiled by all the
steps above. If you have more than one file to compile, just do
something like</para>
<screen>&prompt.user; <userinput>cc foo.c bar.c</>
</screen>
<para>Note that the syntax checking is just that—checking
the syntax. It will not check for any logical mistakes you may
have made, like putting the program into an infinite loop, or
using a bubble sort when you meant to use a binary
sort.
<footnote>
<para>In case you didn't know, a binary sort is an efficient
way of sorting things into order and a bubble sort
isn't.</para>
</footnote></para>
<para>There are lots and lots of options for <command>cc</command>, which
are all in the man page. Here are a few of the most important
ones, with examples of how to use them.</para>
<variablelist>
<varlistentry>
<term><option>-o <replaceable>filename</replaceable></option></term>
<listitem>
<para>The output name of the file. If you do not use this
option, <command>cc</command> will produce an executable called
<filename>a.out</filename>.
<footnote>
<para>The reasons for this are buried in the mists of
history.</para>
</footnote></para>
<informalexample>
<screen>&prompt.user; <userinput>cc foobar.c</> <lineannotation>executable is <filename>a.out</></>
&prompt.user; <userinput>cc -o foobar foobar.c</> <lineannotation>executable is <filename>foobar</></>
</screen>
</informalexample>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-c</option></term>
<listitem>
<para>Just compile the file, do not link it. Useful for toy
programs where you just want to check the syntax, or if
you are using a <filename>Makefile</filename>.</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -c foobar.c</userinput>
</screen>
</informalexample>
<para>This will produce an <firstterm>object file</firstterm> (not an
executable) called <filename>foobar.o</filename>. This
can be linked together with other object files into an
executable.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-g</option></term>
<listitem>
<para>Create a debug version of the executable. This makes
the compiler put information into the executable about
which line of which source file corresponds to which
function call. A debugger can use this information to show
the source code as you step through the program, which is
<emphasis>very</emphasis> useful; the disadvantage is that
all this extra information makes the program much bigger.
Normally, you compile with <option>-g</option> while you
are developing a program and then compile a <quote>release
version</quote> without <option>-g</option> when you're
satisfied it works properly.</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -g foobar.c</userinput>
</screen>
</informalexample>
<para>This will produce a debug version of the
program.
<footnote>
<para>Note, we didn't use the <option>-o</option> flag
to specify the executable name, so we will get an
executable called <filename>a.out</filename>.
Producing a debug version called
<filename>foobar</filename> is left as an exercise for
the reader!</para>
</footnote></para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-O</option></term>
<listitem>
<para>Create an optimised version of the executable. The
compiler performs various clever tricks to try and produce
an executable that runs faster than normal. You can add a
number after the <option>-O</option> to specify a higher
level of optimisation, but this often exposes bugs in the
compiler's optimiser. For instance, the version of
<command>cc</command> that comes with the 2.1.0 release of
FreeBSD is known to produce bad code with the
<option>-O2</option> option in some circumstances.</para>
<para>Optimisation is usually only turned on when compiling
a release version.</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -O -o foobar foobar.c</userinput>
</screen>
</informalexample>
<para>This will produce an optimised version of
<filename>foobar</filename>.</para>
</listitem>
</varlistentry>
</variablelist>
<para>The following three flags will force <command>cc</command>
to check that your code complies to the relevant international
standard, often referred to as the <acronym>ANSI</acronym>
standard, though strictly speaking it is an
<acronym>ISO</acronym> standard.</para>
<variablelist>
<varlistentry>
<term><option>-Wall</option></term>
<listitem>
<para>Enable all the warnings which the authors of
<command>cc</command> believe are worthwhile. Despite the
name, it will not enable all the warnings
<command>cc</command> is capable of.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-ansi</option></term>
<listitem>
<para>Turn off most, but not all, of the
non-<acronym>ANSI</acronym> C features provided by
<command>cc</command>. Despite the name, it does not
guarantee strictly that your code will comply to the
standard.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-pedantic</option></term>
<listitem>
<para>Turn off <emphasis>all</emphasis>
<command>cc</command>'s non-<acronym>ANSI</acronym> C
features.</para>
</listitem>
</varlistentry>
</variablelist>
<para>Without these flags, <command>cc</command> will allow you to
use some of its non-standard extensions to the standard. Some
of these are very useful, but will not work with other
compilers—in fact, one of the main aims of the standard is
to allow people to write code that will work with any compiler
on any system. This is known as <firstterm>portable
code</firstterm>.</para>
<para>Generally, you should try to make your code as portable as
possible, as otherwise you may have to completely re-write the
program later to get it to work somewhere else—and who
knows what you may be using in a few years time?</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -Wall -ansi -pedantic -o foobar foobar.c</userinput>
</screen>
</informalexample>
<para>This will produce an executable <filename>foobar</filename>
after checking <filename>foobar.c</filename> for standard
compliance.</para>
<variablelist>
<varlistentry>
<term><option>-l<replaceable>library</replaceable></option></term>
<listitem>
<para>Specify a function library to be used during when
linking.</para>
<para>The most common example of this is when compiling a
program that uses some of the mathematical functions in C.
Unlike most other platforms, these are in a separate
library from the standard C one and you have to tell the
compiler to add it.</para>
<para>The rule is that if the library is called
<filename>lib<replaceable>something</replaceable>.a</filename>,
you give <command>cc</command> the argument
<option>-l<replaceable>something</replaceable></option>.
For example, the math library is
<filename>libm.a</filename>, so you give
<command>cc</command> the argument <option>-lm</option>.
A common <quote>gotcha</quote> with the math library is
that it has to be the last library on the command
line.</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -o foobar foobar.c -lm</userinput>
</screen>
</informalexample>
<para>This will link the math library functions into
<filename>foobar</filename>.</para>
<para>If you are compiling C++ code, you need to add
<option>-lg++</option>, or <option>-lstdc++</option> if
you are using FreeBSD 2.2 or later, to the command line
argument to link the C++ library functions.
Alternatively, you can run <command>c++</command> instead
of <command>cc</command>, which does this for you.
<command>c++</command> can also be invoked as
<command>g++</command> on FreeBSD.</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -o foobar foobar.cc -lg++</userinput> <lineannotation>For FreeBSD 2.1.6 and earlier</>
&prompt.user; <userinput>cc -o foobar foobar.cc -lstdc++</userinput> <lineannotation>For FreeBSD 2.2 and later</>
&prompt.user; <userinput>c++ -o foobar foobar.cc</userinput>
</screen>
</informalexample>
<para>Each of these will both produce an executable
<filename>foobar</filename> from the C++ source file
<filename>foobar.cc</filename>. Note that, on Unix
systems, C++ source files traditionally end in
<filename>.C</filename>, <filename>.cxx</filename> or
<filename>.cc</filename>, rather than the
MS-DOS style
<filename>.cpp</filename> (which was already used for
something else). <command>gcc</command> used to rely on
this to work out what kind of compiler to use on the
source file; however, this restriction no longer applies,
so you may now call your C++ files
<filename>.cpp</filename> with impunity!</para>
</listitem>
</varlistentry>
</variablelist>
<sect2>
<title>Common <command>cc</command> Queries and Problems</title>
<qandaset>
<qandaentry>
<question>
<para>I am trying to write a program which uses the
<function>sin()</function> function and I get an error
like this. What does it mean?</para>
<informalexample>
<screen>/var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment
</screen>
</informalexample>
</question>
<answer>
<para>When using mathematical functions like
<function>sin()</function>, you have to tell
<command>cc</command> to link in the math library, like
so:</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -o foobar foobar.c -lm</userinput>
</screen>
</informalexample>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>All right, I wrote this simple program to practice
using <option>-lm</option>. All it does is raise 2.1 to
the power of 6.</para>
<informalexample>
<programlisting>#include <stdio.h>
int main() {
float f;
f = pow(2.1, 6);
printf("2.1 ^ 6 = %f\n", f);
return 0;
}
</programlisting>
</informalexample>
<para>and I compiled it as:</para>
<informalexample>
<screen>&prompt.user; <userinput>cc temp.c -lm</userinput>
</screen>
</informalexample>
<para>like you said I should, but I get this when I run
it:</para>
<informalexample>
<screen>&prompt.user; <userinput>./a.out</userinput>
2.1 ^ 6 = 1023.000000
</screen>
</informalexample>
<para>This is <emphasis>not</emphasis> the right answer!
What is going on?</para>
</question>
<answer>
<para>When the compiler sees you call a function, it
checks if it has already seen a prototype for it. If it
has not, it assumes the function returns an
<type>int</type>, which is definitely not what you want
here.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>So how do I fix this?</para>
</question>
<answer>
<para>The prototypes for the mathematical functions are in
<filename>math.h</filename>. If you include this file,
the compiler will be able to find the prototype and it
will stop doing strange things to your
calculation!</para>
<informalexample>
<programlisting>#include <math.h>
#include <stdio.h>
int main() {
...
</programlisting>
</informalexample>
<para>After recompiling it as you did before, run
it:</para>
<informalexample>
<screen>&prompt.user; <userinput>./a.out</userinput>
2.1 ^ 6 = 85.766121
</screen>
</informalexample>
<para>If you are using any of the mathematical functions,
<emphasis>always</emphasis> include
<filename>math.h</filename> and remember to link in the
math library.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>I compiled a file called
<filename>foobar.c</filename> and I cannot find an
executable called <filename>foobar</filename>. Where's
it gone?</para>
</question>
<answer>
<para>Remember, <command>cc</command> will call the
executable <filename>a.out</filename> unless you tell it
differently. Use the
<option>-o <replaceable>filename</replaceable></option>
option:</para>
<informalexample>
<screen>&prompt.user; <userinput>cc -o foobar foobar.c</userinput>
</screen>
</informalexample>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>OK, I have an executable called
<filename>foobar</filename>, I can see it when I run
<command>ls</command>, but when I type in
<command>foobar</command> at the command prompt it tells
me there is no such file. Why can it not find
it?</para>
</question>
<answer>
<para>Unlike MS-DOS, Unix does not
look in the current directory when it is trying to find
out which executable you want it to run, unless you tell
it to. Either type <command>./foobar</command>, which
means <quote>run the file called
<filename>foobar</filename> in the current
directory</quote>, or change your <systemitem
class=environvar>PATH</systemitem> environment
variable so that it looks something like</para>
<informalexample>
<screen>bin:/usr/bin:/usr/local/bin:.
</screen>
</informalexample>
<para>The dot at the end means <quote>look in the current
directory if it is not in any of the
others</quote>.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>I called my executable <filename>test</filename>,
but nothing happens when I run it. What is going
on?</para>
</question>
<answer>
<para>Most Unix systems have a program called
<command>test</command> in <filename>/usr/bin</filename>
and the shell is picking that one up before it gets to
checking the current directory. Either type:</para>
<informalexample>
<screen>&prompt.user; <userinput>./test</userinput>
</screen>
</informalexample>
<para>or choose a better name for your program!</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>I compiled my program and it seemed to run all right
at first, then there was an error and it said something
about <errorname>core dumped</errorname>. What does that
mean?</para>
</question>
<answer>
<para>The name <firstterm>core dump</firstterm> dates back
to the very early days of Unix, when the machines used
core memory for storing data. Basically, if the program
failed under certain conditions, the system would write
the contents of core memory to disk in a file called
<filename>core</filename>, which the programmer could
then pore over to find out what went wrong.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>Fascinating stuff, but what I am supposed to do
now?</para>
</question>
<answer>
<para>Use <command>gdb</command> to analyse the core (see
<xref linkend="debugging">).</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>When my program dumped core, it said something about
a <errorname>segmentation fault</errorname>. What's
that?</para>
</question>
<answer>
<para>This basically means that your program tried to
perform some sort of illegal operation on memory; Unix
is designed to protect the operating system and other
programs from rogue programs.</para>
<para>Common causes for this are:</para>
<itemizedlist>
<listitem>
<para>Trying to write to a <symbol>NULL</symbol>
pointer, eg</para>
<programlisting>char *foo = NULL;
strcpy(foo, "bang!");
</programlisting>
</listitem>
<listitem>
<para>Using a pointer that hasn't been initialised,
eg</para>
<programlisting>char *foo;
strcpy(foo, "bang!");
</programlisting>
<para>The pointer will have some random value that,
with luck, will point into an area of memory that
isn't available to your program and the kernel will
kill your program before it can do any damage. If
you're unlucky, it'll point somewhere inside your
own program and corrupt one of your data structures,
causing the program to fail mysteriously.</para>
</listitem>
<listitem>
<para>Trying to access past the end of an array,
eg</para>
<programlisting>int bar[20];
bar[27] = 6;
</programlisting>
</listitem>
<listitem>
<para>Trying to store something in read-only memory,
eg</para>
<programlisting>char *foo = "My string";
strcpy(foo, "bang!");
</programlisting>
<para>Unix compilers often put string literals like
<literal>"My string"</literal> into read-only areas
of memory.</para>
</listitem>
<listitem>
<para>Doing naughty things with
<function>malloc()</function> and
<function>free()</function>, eg</para>
<programlisting>char bar[80];
free(bar);
</programlisting>
<para>or</para>
<programlisting>char *foo = malloc(27);
free(foo);
free(foo);
</programlisting>
</listitem>
</itemizedlist>
<para>Making one of these mistakes will not always lead to
an error, but they are always bad practice. Some
systems and compilers are more tolerant than others,
which is why programs that ran well on one system can
crash when you try them on an another.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>Sometimes when I get a core dump it says
<errorname>bus error</errorname>. It says in my Unix
book that this means a hardware problem, but the
computer still seems to be working. Is this
true?</para>
</question>
<answer>
<para>No, fortunately not (unless of course you really do
have a hardware problem…). This is usually
another way of saying that you accessed memory in a way
you shouldn't have.</para>
</answer>
</qandaentry>
<qandaentry>
<question>
<para>This dumping core business sounds as though it could
be quite useful, if I can make it happen when I want to.
Can I do this, or do I have to wait until there's an
error?</para>
</question>
<answer>
<para>Yes, just go to another console or xterm, do</para>
<screen>&prompt.user; <userinput>ps</userinput>
</screen>
<para>to find out the process ID of your program, and
do</para>
<screen>&prompt.user; <userinput>kill -ABRT <replaceable>pid</replaceable></userinput>
</screen>
<para>where
<parameter><replaceable>pid</replaceable></parameter> is
the process ID you looked up.</para>
<para>This is useful if your program has got stuck in an
infinite loop, for instance. If your program happens to
trap <symbol>SIGABRT</symbol>, there are several other
signals which have a similar effect.</para>
</answer>
</qandaentry>
</qandaset>
</sect2>
</sect1>
<sect1>
<title>Make</title>
<sect2>
<title>What is <command>make</command>?</title>
<para>When you're working on a simple program with only one or
two source files, typing in</para>
<screen>&prompt.user; <userinput>cc file1.c file2.c</userinput>
</screen>
<para>is not too bad, but it quickly becomes very tedious when
there are several files—and it can take a while to
compile, too.</para>
<para>One way to get around this is to use object files and only
recompile the source file if the source code has changed. So
we could have something like:</para>
<screen>&prompt.user; <userinput>cc file1.o file2.o</userinput> … <userinput>file37.c</userinput> &hellip
</screen>
<para>if we'd changed <filename>file37.c</filename>, but not any
of the others, since the last time we compiled. This may
speed up the compilation quite a bit, but doesn't solve the
typing problem.</para>
<para>Or we could write a shell script to solve the typing
problem, but it would have to re-compile everything, making it
very inefficient on a large project.</para>
<para>What happens if we have hundreds of source files lying
about? What if we're working in a team with other people who
forget to tell us when they've changed one of their source
files that we use?</para>
<para>Perhaps we could put the two solutions together and write
something like a shell script that would contain some kind of
magic rule saying when a source file needs compiling. Now all
we need now is a program that can understand these rules, as
it's a bit too complicated for the shell.</para>
<para>This program is called <command>make</command>. It reads
in a file, called a <firstterm>makefile</firstterm>, that
tells it how different files depend on each other, and works
out which files need to be re-compiled and which ones don't.
For example, a rule could say something like <quote>if
<filename>fromboz.o</filename> is older than
<filename>fromboz.c</filename>, that means someone must have
changed <filename>fromboz.c</filename>, so it needs to be
re-compiled.</quote> The makefile also has rules telling
make <emphasis>how</emphasis> to re-compile the source file,
making it a much more powerful tool.</para>
<para>Makefiles are typically kept in the same directory as the
source they apply to, and can be called
<filename>makefile</filename>, <filename>Makefile</filename>
or <filename>MAKEFILE</filename>. Most programmers use the
name <filename>Makefile</filename>, as this puts it near the
top of a directory listing, where it can easily be
seen.
<footnote>
<para>They don't use the <filename>MAKEFILE</filename> form
as block capitals are often used for documentation files
like <filename>README</filename>.</para>
</footnote></para>
</sect2>
<sect2>
<title>Example of using <command>make</command></title>
<para>Here's a very simple make file:</para>
<programlisting>foo: foo.c
cc -o foo foo.c
</programlisting>
<para>It consists of two lines, a dependency line and a creation
line.</para>
<para>The dependency line here consists of the name of the
program (known as the <firstterm>target</firstterm>), followed
by a colon, then whitespace, then the name of the source file.
When <command>make</command> reads this line, it looks to see
if <filename>foo</filename> exists; if it exists, it compares
the time <filename>foo</filename> was last modified to the
time <filename>foo.c</filename> was last modified. If
<filename>foo</filename> does not exist, or is older than
<filename>foo.c</filename>, it then looks at the creation line
to find out what to do. In other words, this is the rule for
working out when <filename>foo.c</filename> needs to be
re-compiled.</para>
<para>The creation line starts with a <token>tab</token> (press
the <keycap>tab</keycap> key) and then the command you would
type to create <filename>foo</filename> if you were doing it
at a command prompt. If <filename>foo</filename> is out of
date, or does not exist, <command>make</command> then executes
this command to create it. In other words, this is the rule
which tells make how to re-compile
<filename>foo.c</filename>.</para>
<para>So, when you type <userinput>make</userinput>, it will
make sure that <filename>foo</filename> is up to date with
respect to your latest changes to <filename>foo.c</filename>.
This principle can be extended to
<filename>Makefile</filename>s with hundreds of
targets—in fact, on FreeBSD, it is possible to compile
the entire operating system just by typing <userinput>make
world</userinput> in the appropriate directory!</para>
<para>Another useful property of makefiles is that the targets
don't have to be programs. For instance, we could have a make
file that looks like this:</para>
<programlisting>foo: foo.c
cc -o foo foo.c
install:
cp foo /home/me
</programlisting>
<para>We can tell make which target we want to make by
typing:</para>
<screen>&prompt.user; <userinput>make <replaceable>target</replaceable></userinput>
</screen>
<para><command>make</command> will then only look at that target
and ignore any others. For example, if we type
<userinput>make foo</userinput> with the makefile above, make
will ignore the <action>install</action> target.</para>
<para>If we just type <userinput>make</userinput> on its own,
make will always look at the first target and then stop
without looking at any others. So if we typed
<userinput>make</userinput> here, it will just go to the
<action>foo</action> target, re-compile
<filename>foo</filename> if necessary, and then stop without
going on to the <action>install</action> target.</para>
<para>Notice that the <action>install</action> target doesn't
actually depend on anything! This means that the command on
the following line is always executed when we try to make that
target by typing <userinput>make install</userinput>. In this
case, it will copy <filename>foo</filename> into the user's
home directory. This is often used by application makefiles,
so that the application can be installed in the correct
directory when it has been correctly compiled.</para>
<para>This is a slightly confusing subject to try and explain.
If you don't quite understand how <command>make</command>
works, the best thing to do is to write a simple program like
<quote>hello world</quote> and a make file like the one above
and experiment. Then progress to using more than one source
file, or having the source file include a header file. The
<command>touch</command> command is very useful here—it
changes the date on a file without you having to edit
it.</para>
</sect2>
<sect2>
<title>FreeBSD Makefiles</title>
<para>Makefiles can be rather complicated to write. Fortunately,
BSD-based systems like FreeBSD come with some very powerful
ones as part of the system. One very good example of this is
the FreeBSD ports system. Here's the essential part of a
typical ports <filename>Makefile</filename>:</para>
<programlisting>MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/
DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz
.include <bsd.port.mk>
</programlisting>
<para>Now, if we go to the directory for this port and type
<userinput>make</userinput>, the following happens:</para>
<procedure>
<step>
<para>A check is made to see if the source code for this
port is already on the system.</para>
</step>
<step>
<para>If it isn't, an FTP connection to the URL in
<symbol>MASTER_SITES</symbol> is set up to download the
source.</para>
</step>
<step>
<para>The checksum for the source is calculated and compared
it with one for a known, good, copy of the source. This
is to make sure that the source was not corrupted while in
transit.</para>
</step>
<step>
<para>Any changes required to make the source work on
FreeBSD are applied—this is known as
<firstterm>patching</firstterm>.</para>
</step>
<step>
<para>Any special configuration needed for the source is
done. (Many Unix program distributions try to work out
which version of Unix they are being compiled on and which
optional Unix features are present—this is where
they are given the information in the FreeBSD ports
scenario).</para>
</step>
<step>
<para>The source code for the program is compiled. In
effect, we change to the directory where the source was
unpacked and do <command>make</command>—the
program's own make file has the necessary information to
build the program.</para>
</step>
<step>
<para>We now have a compiled version of the program. If we
wish, we can test it now; when we feel confident about the
program, we can type <userinput>make install</userinput>.
This will cause the program and any supporting files it
needs to be copied into the correct location; an entry is
also made into a <database>package database</database>, so
that the port can easily be uninstalled later if we change
our mind about it.</para>
</step>
</procedure>
<para>Now I think you'll agree that's rather impressive for a
four line script!</para>
<para>The secret lies in the last line, which tells
<command>make</command> to look in the system makefile called
<filename>bsd.port.mk</filename>. It's easy to overlook this
line, but this is where all the clever stuff comes
from—someone has written a makefile that tells
<command>make</command> to do all the things above (plus a
couple of other things I didn't mention, including handling
any errors that may occur) and anyone can get access to that
just by putting a single line in their own make file!</para>
<para>If you want to have a look at these system makefiles,
they're in <filename>/usr/share/mk</filename>, but it's
probably best to wait until you've had a bit of practice with
makefiles, as they are very complicated (and if you do look at
them, make sure you have a flask of strong coffee
handy!)</para>
</sect2>
<sect2>
<title>More advanced uses of <command>make</command></title>
<para><command>Make</command> is a very powerful tool, and can
do much more than the simple example above shows.
Unfortunately, there are several different versions of
<command>make</command>, and they all differ considerably.
The best way to learn what they can do is probably to read the
documentation—hopefully this introduction will have
given you a base from which you can do this.</para>
<para>The version of make that comes with FreeBSD is the
<application>Berkeley make</application>; there is a tutorial
for it in <filename>/usr/share/doc/psd/12.make</filename>. To
view it, do</para>
<screen>&prompt.user; <userinput>zmore paper.ascii.gz</userinput>
</screen>
<para>in that directory.</para>
<para>Many applications in the ports use <application>GNU
make</application>, which has a very good set of
<quote>info</quote> pages. If you have installed any of these
ports, <application>GNU make</application> will automatically
have been installed as <command>gmake</command>. It's also
available as a port and package in its own right.</para>
<para>To view the info pages for <application>GNU
make</application>, you will have to edit the
<filename>dir</filename> file in the
<filename>/usr/local/info</filename> directory to add an entry
for it. This involves adding a line like</para>
<programlisting> * Make: (make). The GNU Make utility.
</programlisting>
<para>to the file. Once you have done this, you can type
<userinput>info</userinput> and then select
<guimenuitem>make</guimenuitem> from the menu (or in
<application>Emacs</application>, do <userinput>C-h
i</userinput>).</para>
</sect2>
</sect1>
<sect1 id="debugging">
<title>Debugging</title>
<sect2>
<title>The Debugger</title>
<para>The debugger that comes with FreeBSD is called
<command>gdb</command> (<application>GNU
debugger</application>). You start it up by typing</para>
<screen>&prompt.user; <userinput>gdb <replaceable>progname</replaceable></userinput>
</screen>
<para>although most people prefer to run it inside
<application>Emacs</application>. You can do this by:</para>
<screen><userinput>M-x gdb RET <replaceable>progname</replaceable> RET</userinput>
</screen>
<para>Using a debugger allows you to run the program under more
controlled circumstances. Typically, you can step through the
program a line at a time, inspect the value of variables,
change them, tell the debugger to run up to a certain point
and then stop, and so on. You can even attach to a program
that's already running, or load a core file to investigate why
the program crashed. It's even possible to debug the kernel,
though that's a little trickier than the user applications
we'll be discussing in this section.</para>
<para><command>gdb</command> has quite good on-line help, as
well as a set of info pages, so this section will concentrate
on a few of the basic commands.</para>
<para>Finally, if you find its text-based command-prompt style
off-putting, there's a graphical front-end for it <ulink
URL="../../ports/devel.html">xxgdb</ulink> in the ports
collection.</para>
<para>This section is intended to be an introduction to using
<command>gdb</command> and does not cover specialised topics
such as debugging the kernel.</para>
</sect2>
<sect2>
<title>Running a program in the debugger</title>
<para>You'll need to have compiled the program with the
<option>-g</option> option to get the most out of using
<command>gdb</command>. It will work without, but you'll only
see the name of the function you're in, instead of the source
code. If you see a line like:</para>
<screen>… (no debugging symbols found) …
</screen>
<para>when <command>gdb</command> starts up, you'll know that
the program wasn't compiled with the <option>-g</option>
option.</para>
<para>At the <command>gdb</command> prompt, type
<userinput>break main</userinput>. This will tell the
debugger to skip over the preliminary set-up code in the
program and start at the beginning of your code. Now type
<userinput>run</userinput> to start the program—it will
start at the beginning of the set-up code and then get stopped
by the debugger when it calls <function>main()</function>.
(If you've ever wondered where <function>main()</function>
gets called from, now you know!).</para>
<para>You can now step through the program, a line at a time, by
pressing <command>n</command>. If you get to a function call,
you can step into it by pressing <command>s</command>. Once
you're in a function call, you can return from stepping into a
function call by pressing <command>f</command>. You can also
use <command>up</command> and <command>down</command> to take
a quick look at the caller.</para>
<para>Here's a simple example of how to spot a mistake in a
program with <command>gdb</command>. This is our program
(with a deliberate mistake):</para>
<programlisting>#include <stdio.h>
int bazz(int anint);
main() {
int i;
printf("This is my program\n");
bazz(i);
return 0;
}
int bazz(int anint) {
printf("You gave me %d\n", anint);
return anint;
}
</programlisting>
<para>This program sets <symbol>i</symbol> to be
<literal>5</literal> and passes it to a function
<function>bazz()</function> which prints out the number we
gave it.</para>
<para>When we compile and run the program we get</para>
<screen>&prompt.user; <userinput>cc -g -o temp temp.c</userinput>
&prompt.user; <userinput>./temp</userinput>
This is my program
anint = 4231
</screen>
<para>That wasn't what we expected! Time to see what's going
on!</para>
<screen>&prompt.user; <userinput>gdb temp</userinput>
GDB is free software and you are welcome to distribute copies of it
under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) <userinput>break main</> <lineannotation>Skip the set-up code</>
Breakpoint 1 at 0x160f: file temp.c, line 9. <lineannotation><command>gdb</command> puts breakpoint at <function>main()</></>
(gdb) <userinput>run</> <lineannotation>Run as far as <function>main()</></>
Starting program: /home/james/tmp/temp <lineannotation>Program starts running</>
Breakpoint 1, main () at temp.c:9 <lineannotation><command>gdb</command> stops at <function>main()</></>
(gdb) <userinput>n</> <lineannotation>Go to next line</>
This is my program <lineannotation>Program prints out</>
(gdb) <userinput>s</> <lineannotation>step into <function>bazz()</></>
bazz (anint=4231) at temp.c:17 <lineannotation><command>gdb</command> displays stack frame</>
(gdb)
</screen>
<para>Hang on a minute! How did <symbol>anint</symbol> get to be
<literal>4231</literal>? Didn't we set it to be
<literal>5</literal> in <function>main()</function>? Let's
move up to <function>main()</function> and have a look.</para>
<screen>(gdb) <userinput>up</> <lineannotation>Move up call stack</>
#1 0x1625 in main () at temp.c:11 <lineannotation><command>gdb</command> displays stack frame</>
(gdb) <userinput>p i</> <lineannotation>Show us the value of <symbol>i</></>
$1 = 4231 <lineannotation><command>gdb</command> displays <literal>4231</></>
</screen>
<para>Oh dear! Looking at the code, we forgot to initialise
<symbol>i</symbol>. We meant to put</para>
<programlisting><lineannotation>…</>
main() {
int i;
i = 5;
printf("This is my program\n");
<lineannotation>&hellip</>
</programlisting>
<para>but we left the <literal>i=5;</literal> line out. As we
didn't initialise <symbol>i</symbol>, it had whatever number
happened to be in that area of memory when the program ran,
which in this case happened to be
<literal>4231</literal>.</para>
<note>
<para><command>gdb</command> displays the stack frame every
time we go into or out of a function, even if we're using
<command>up</command> and <command>down</command> to move
around the call stack. This shows the name of the function
and the values of its arguments, which helps us keep track
of where we are and what's going on. (The stack is a
storage area where the program stores information about the
arguments passed to functions and where to go when it
returns from a function call).</para>
</note>
</sect2>
<sect2>
<title>Examining a core file</title>
<para>A core file is basically a file which contains the
complete state of the process when it crashed. In <quote>the
good old days</quote>, programmers had to print out hex
listings of core files and sweat over machine code manuals,
but now life is a bit easier. Incidentally, under FreeBSD and
other 4.4BSD systems, a core file is called
<filename><replaceable>progname</replaceable>.core</filename> instead of just
<filename>core</filename>, to make it clearer which program a
core file belongs to.</para>
<para>To examine a core file, start up <command>gdb</command> in
the usual way. Instead of typing <command>break</command> or
<command>run</command>, type</para>
<screen>(gdb) <userinput>core <replaceable>progname</replaceable>.core</userinput>
</screen>
<para>If you're not in the same directory as the core file,
you'll have to do <userinput>dir
/path/to/core/file</userinput> first.</para>
<para>You should see something like this:</para>
<screen>&prompt.user; <userinput>gdb a.out</userinput>
GDB is free software and you are welcome to distribute copies of it
under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) <userinput>core a.out.core</userinput>
Core was generated by `a.out'.
Program terminated with signal 11, Segmentation fault.
Cannot access memory at address 0x7020796d.
#0 0x164a in bazz (anint=0x5) at temp.c:17
(gdb)
</screen>
<para>In this case, the program was called
<filename>a.out</filename>, so the core file is called
<filename>a.out.core</filename>. We can see that the program
crashed due to trying to access an area in memory that was not
available to it in a function called
<function>bazz</function>.</para>
<para>Sometimes it's useful to be able to see how a function was
called, as the problem could have occurred a long way up the
call stack in a complex program. The <command>bt</command>
command causes <command>gdb</command> to print out a
back-trace of the call stack:</para>
<screen>(gdb) <userinput>bt</userinput>
#0 0x164a in bazz (anint=0x5) at temp.c:17
#1 0xefbfd888 in end ()
#2 0x162c in main () at temp.c:11
(gdb)
</screen>
<para>The <function>end()</function> function is called when a
program crashes; in this case, the <function>bazz()</function>
function was called from <function>main()</function>.</para>
</sect2>
<sect2>
<title>Attaching to a running program</title>
<para>One of the neatest features about <command>gdb</command>
is that it can attach to a program that's already running. Of
course, that assumes you have sufficient permissions to do so.
A common problem is when you are stepping through a program
that forks, and you want to trace the child, but the debugger
will only let you trace the parent.</para>
<para>What you do is start up another <command>gdb</command>,
use <command>ps</command> to find the process ID for the
child, and do</para>
<screen>(gdb) <userinput>attach <replaceable>pid</replaceable></userinput>
</screen>
<para>in <command>gdb</command>, and then debug as usual.</para>
<para><quote>That's all very well,</quote> you're probably
thinking, <quote>but by the time I've done that, the child
process will be over the hill and far away</quote>. Fear
not, gentle reader, here's how to do it (courtesy of the
<command>gdb</command> info pages):</para>
<screen><lineannotation>&hellip</lineannotation>
if ((pid = fork()) < 0) /* _Always_ check this */
error();
else if (pid == 0) { /* child */
int PauseMode = 1;
while (PauseMode)
sleep(10); /* Wait until someone attaches to us */
<lineannotation>&hellip</lineannotation>
} else { /* parent */
<lineannotation>&hellip</lineannotation>
</screen>
<para>Now all you have to do is attach to the child, set
<symbol>PauseMode</symbol> to <literal>0</literal>, and wait
for the <function>sleep()</function> call to return!</para>
</sect2>
</sect1>
<sect1 id="emacs">
<title>Using Emacs as a Development Environment</title>
<sect2>
<title>Emacs</title>
<para>Unfortunately, Unix systems don't come with the kind of
everything-you-ever-wanted-and-lots-more-you-didn't-in-one-gigantic-package
integrated development environments that other systems
have.
<footnote>
<para>At least, not unless you pay out very large sums of
money.</para>
</footnote>
However, it is possible to set up your own environment. It
may not be as pretty, and it may not be quite as integrated,
but you can set it up the way you want it. And it's free.
And you have the source to it.</para>
<para>The key to it all is Emacs. Now there are some people who
loathe it, but many who love it. If you're one of the former,
I'm afraid this section will hold little of interest to you.
Also, you'll need a fair amount of memory to run it—I'd
recommend 8MB in text mode and 16MB in X as the bare minimum
to get reasonable performance.</para>
<para>Emacs is basically a highly customisable
editor—indeed, it has been customised to the point where
it's more like an operating system than an editor! Many
developers and sysadmins do in fact spend practically all
their time working inside Emacs, leaving it only to log
out.</para>
<para>It's impossible even to summarise everything Emacs can do
here, but here are some of the features of interest to
developers:</para>
<itemizedlist>
<listitem>
<para>Very powerful editor, allowing search-and-replace on
both strings and regular expressions (patterns), jumping
to start/end of block expression, etc, etc.</para>
</listitem>
<listitem>
<para>Pull-down menus and online help.</para>
</listitem>
<listitem>
<para>Language-dependent syntax highlighting and
indentation.</para>
</listitem>
<listitem>
<para>Completely customisable.</para>
</listitem>
<listitem>
<para>You can compile and debug programs within
Emacs.</para>
</listitem>
<listitem>
<para>On a compilation error, you can jump to the offending
line of source code.</para>
</listitem>
<listitem>
<para>Friendly-ish front-end to the <command>info</command>
program used for reading GNU hypertext documentation,
including the documentation on Emacs itself.</para>
</listitem>
<listitem>
<para>Friendly front-end to <command>gdb</command>, allowing
you to look at the source code as you step through your
program.</para>
</listitem>
<listitem>
<para>You can read Usenet news and mail while your program
is compiling.</para>
</listitem>
</itemizedlist>
<para>And doubtless many more that I've overlooked.</para>
<para>Emacs can be installed on FreeBSD using <ulink
URL="../../ports/editors.html">the Emacs
port</ulink>.</para>
<para>Once it's installed, start it up and do <userinput>C-h
t</userinput> to read an Emacs tutorial—that means
hold down the <keycap>control</keycap> key, press
<keycap>h</keycap>, let go of the <keycap>control</keycap>
key, and then press <keycap>t</keycap>. (Alternatively, you
can you use the mouse to select <guimenuitem>Emacs
Tutorial</guimenuitem> from the <guimenu>Help</guimenu>
menu).</para>
<para>Although Emacs does have menus, it's well worth learning
the key bindings, as it's much quicker when you're editing
something to press a couple of keys than to try and find the
mouse and then click on the right place. And, when you're
talking to seasoned Emacs users, you'll find they often
casually throw around expressions like <quote><literal>M-x
replace-s RET foo RET bar RET</literal></quote> so it's
useful to know what they mean. And in any case, Emacs has far
too many useful functions for them to all fit on the menu
bars.</para>
<para>Fortunately, it's quite easy to pick up the key-bindings,
as they're displayed next to the menu item. My advice is to
use the menu item for, say, opening a file until you
understand how it works and feel confident with it, then try
doing C-x C-f. When you're happy with that, move on to
another menu command.</para>
<para>If you can't remember what a particular combination of
keys does, select <guimenuitem>Describe Key</guimenuitem> from
the <guimenu>Help</guimenu> menu and type it in—Emacs
will tell you what it does. You can also use the
<guimenuitem>Command Apropos</guimenuitem> menu item to find
out all the commands which contain a particular word in them,
with the key binding next to it.</para>
<para>By the way, the expression above means hold down the
<keysym>Meta</keysym> key, press <keysym>x</keysym>, release
the <keysym>Meta</keysym> key, type
<userinput>replace-s</userinput> (short for
<literal>replace-string</literal>—another feature of
Emacs is that you can abbreviate commands), press the
<keysym>return</keysym> key, type <userinput>foo</userinput>
(the string you want replaced), press the
<keysym>return</keysym> key, type bar (the string you want to
replace <literal>foo</literal> with) and press
<keysym>return</keysym> again. Emacs will then do the
search-and-replace operation you've just requested.</para>
<para>If you're wondering what on earth the
<keysym>Meta</keysym> key is, it's a special key that many
Unix workstations have. Unfortunately, PC's don't have one,
so it's usually the <keycap>alt</keycap> key (or if you're
unlucky, the <keysym>escape</keysym> key).</para>
<para>Oh, and to get out of Emacs, do <command>C-x C-c</command>
(that means hold down the <keysym>control</keysym> key, press
<keysym>x</keysym>, press <keysym>c</keysym> and release the
<keysym>control</keysym> key). If you have any unsaved files
open, Emacs will ask you if you want to save them. (Ignore
the bit in the documentation where it says
<command>C-z</command> is the usual way to leave
Emacs—that leaves Emacs hanging around in the
background, and is only really useful if you're on a system
which doesn't have virtual terminals).</para>
</sect2>
<sect2>
<title>Configuring Emacs</title>
<para>Emacs does many wonderful things; some of them are built
in, some of them need to be configured.</para>
<para>Instead of using a proprietary macro language for
configuration, Emacs uses a version of Lisp specially adapted
for editors, known as Emacs Lisp. This can be quite useful if
you want to go on and learn something like Common Lisp, as
it's considerably smaller than Common Lisp (although still
quite big!).</para>
<para>The best way to learn Emacs Lisp is to download the <ulink
URL="ftp://prep.ai.mit.edu:pub/gnu/elisp-manual-19-2.4.tar.gz">Emacs
Tutorial</ulink></para>
<para>However, there's no need to actually know any Lisp to get
started with configuring Emacs, as I've included a sample
<filename>.emacs</filename> file, which should be enough to
get you started. Just copy it into your home directory and
restart Emacs if it's already running; it will read the
commands from the file and (hopefully) give you a useful basic
setup.</para>
</sect2>
<sect2>
<title>A sample <filename>.emacs</filename> file</title>
<para>Unfortunately, there's far too much here to explain it in
detail; however there are one or two points worth
mentioning.</para>
<itemizedlist>
<listitem>
<para>Everything beginning with a <literal>;</literal> is a comment
and is ignored by Emacs.</para>
</listitem>
<listitem>
<para>In the first line, the
<literal>-*- Emacs-Lisp -*-</literal> is so that
we can edit the <filename>.emacs</filename> file itself
within Emacs and get all the fancy features for editing
Emacs Lisp. Emacs usually tries to guess this based on
the filename, and may not get it right for
<filename>.emacs</filename>.</para>
</listitem>
<listitem>
<para>The <keysym>tab</keysym> key is bound to an
indentation function in some modes, so when you press the
tab key, it will indent the current line of code. If you
want to put a <token>tab</token> character in whatever
you're writing, hold the <keysym>control</keysym> key down
while you're pressing the <keysym>tab</keysym> key.</para>
</listitem>
<listitem>
<para>This file supports syntax highlighting for C, C++,
Perl, Lisp and Scheme, by guessing the language from the
filename.</para>
</listitem>
<listitem>
<para>Emacs already has a pre-defined function called
<function>next-error</function>. In a compilation output
window, this allows you to move from one compilation error
to the next by doing <command>M-n</command>; we define a
complementary function,
<function>previous-error</function>, that allows you to go
to a previous error by doing <command>M-p</command>. The
nicest feature of all is that <command>C-c C-c</command>
will open up the source file in which the error occurred
and jump to the appropriate line.</para>
</listitem>
<listitem>
<para>We enable Emacs's ability to act as a server, so that
if you're doing something outside Emacs and you want to
edit a file, you can just type in</para>
<screen>&prompt.user; <userinput>emacsclient <replaceable>filename</replaceable></userinput>
</screen>
<para>and then you can edit the file in your
Emacs!
<footnote>
<para>Many Emacs users set their <systemitem
class=environvar>EDITOR</systemitem> environment to
<literal>emacsclient</literal> so this happens every
time they need to edit a file.</para>
</footnote></para>
</listitem>
</itemizedlist>
<example>
<title>A sample <filename>.emacs</filename> file</title>
<programlisting>;; -*-Emacs-Lisp-*-
;; This file is designed to be re-evaled; use the variable first-time
;; to avoid any problems with this.
(defvar first-time t
"Flag signifying this is the first time that .emacs has been evaled")
;; Meta
(global-set-key "\M- " 'set-mark-command)
(global-set-key "\M-\C-h" 'backward-kill-word)
(global-set-key "\M-\C-r" 'query-replace)
(global-set-key "\M-r" 'replace-string)
(global-set-key "\M-g" 'goto-line)
(global-set-key "\M-h" 'help-command)
;; Function keys
(global-set-key [f1] 'manual-entry)
(global-set-key [f2] 'info)
(global-set-key [f3] 'repeat-complex-command)
(global-set-key [f4] 'advertised-undo)
(global-set-key [f5] 'eval-current-buffer)
(global-set-key [f6] 'buffer-menu)
(global-set-key [f7] 'other-window)
(global-set-key [f8] 'find-file)
(global-set-key [f9] 'save-buffer)
(global-set-key [f10] 'next-error)
(global-set-key [f11] 'compile)
(global-set-key [f12] 'grep)
(global-set-key [C-f1] 'compile)
(global-set-key [C-f2] 'grep)
(global-set-key [C-f3] 'next-error)
(global-set-key [C-f4] 'previous-error)
(global-set-key [C-f5] 'display-faces)
(global-set-key [C-f8] 'dired)
(global-set-key [C-f10] 'kill-compilation)
;; Keypad bindings
(global-set-key [up] "\C-p")
(global-set-key [down] "\C-n")
(global-set-key [left] "\C-b")
(global-set-key [right] "\C-f")
(global-set-key [home] "\C-a")
(global-set-key [end] "\C-e")
(global-set-key [prior] "\M-v")
(global-set-key [next] "\C-v")
(global-set-key [C-up] "\M-\C-b")
(global-set-key [C-down] "\M-\C-f")
(global-set-key [C-left] "\M-b")
(global-set-key [C-right] "\M-f")
(global-set-key [C-home] "\M-<")
(global-set-key [C-end] "\M->")
(global-set-key [C-prior] "\M-<")
(global-set-key [C-next] "\M->")
;; Mouse
(global-set-key [mouse-3] 'imenu)
;; Misc
(global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab.
(setq backup-by-copying-when-mismatch t)
;; Treat 'y' or <CR> as yes, 'n' as no.
(fset 'yes-or-no-p 'y-or-n-p)
(define-key query-replace-map [return] 'act)
(define-key query-replace-map [?\C-m] 'act)
;; Load packages
(require 'desktop)
(require 'tar-mode)
;; Pretty diff mode
(autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t)
(autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t)
(autoload 'ediff-files-remote "ediff"
"Intelligent Emacs interface to diff")
(if first-time
(setq auto-mode-alist
(append '(("\\.cpp$" . c++-mode)
("\\.hpp$" . c++-mode)
("\\.lsp$" . lisp-mode)
("\\.scm$" . scheme-mode)
("\\.pl$" . perl-mode)
) auto-mode-alist)))
;; Auto font lock mode
(defvar font-lock-auto-mode-list
(list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode)
"List of modes to always start in font-lock-mode")
(defvar font-lock-mode-keyword-alist
'((c++-c-mode . c-font-lock-keywords)
(perl-mode . perl-font-lock-keywords))
"Associations between modes and keywords")
(defun font-lock-auto-mode-select ()
"Automatically select font-lock-mode if the current major mode is
in font-lock-auto-mode-list"
(if (memq major-mode font-lock-auto-mode-list)
(progn
(font-lock-mode t))
)
)
(global-set-key [M-f1] 'font-lock-fontify-buffer)
;; New dabbrev stuff
;(require 'new-dabbrev)
(setq dabbrev-always-check-other-buffers t)
(setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_")
(add-hook 'emacs-lisp-mode-hook
'(lambda ()
(set (make-local-variable 'dabbrev-case-fold-search) nil)
(set (make-local-variable 'dabbrev-case-replace) nil)))
(add-hook 'c-mode-hook
'(lambda ()
(set (make-local-variable 'dabbrev-case-fold-search) nil)
(set (make-local-variable 'dabbrev-case-replace) nil)))
(add-hook 'text-mode-hook
'(lambda ()
(set (make-local-variable 'dabbrev-case-fold-search) t)
(set (make-local-variable 'dabbrev-case-replace) t)))
;; C++ and C mode...
(defun my-c++-mode-hook ()
(setq tab-width 4)
(define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
(define-key c++-mode-map "\C-ce" 'c-comment-edit)
(setq c++-auto-hungry-initial-state 'none)
(setq c++-delete-function 'backward-delete-char)
(setq c++-tab-always-indent t)
(setq c-indent-level 4)
(setq c-continued-statement-offset 4)
(setq c++-empty-arglist-indent 4))
(defun my-c-mode-hook ()
(setq tab-width 4)
(define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent)
(define-key c-mode-map "\C-ce" 'c-comment-edit)
(setq c-auto-hungry-initial-state 'none)
(setq c-delete-function 'backward-delete-char)
(setq c-tab-always-indent t)
;; BSD-ish indentation style
(setq c-indent-level 4)
(setq c-continued-statement-offset 4)
(setq c-brace-offset -4)
(setq c-argdecl-indent 0)
(setq c-label-offset -4))
;; Perl mode
(defun my-perl-mode-hook ()
(setq tab-width 4)
(define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
(setq perl-indent-level 4)
(setq perl-continued-statement-offset 4))
;; Scheme mode...
(defun my-scheme-mode-hook ()
(define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent))
;; Emacs-Lisp mode...
(defun my-lisp-mode-hook ()
(define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent)
(define-key lisp-mode-map "\C-i" 'lisp-indent-line)
(define-key lisp-mode-map "\C-j" 'eval-print-last-sexp))
;; Add all of the hooks...
(add-hook 'c++-mode-hook 'my-c++-mode-hook)
(add-hook 'c-mode-hook 'my-c-mode-hook)
(add-hook 'scheme-mode-hook 'my-scheme-mode-hook)
(add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook)
(add-hook 'lisp-mode-hook 'my-lisp-mode-hook)
(add-hook 'perl-mode-hook 'my-perl-mode-hook)
;; Complement to next-error
(defun previous-error (n)
"Visit previous compilation error message and corresponding source code."
(interactive "p")
(next-error (- n)))
;; Misc...
(transient-mark-mode 1)
(setq mark-even-if-inactive t)
(setq visible-bell nil)
(setq next-line-add-newlines nil)
(setq compile-command "make")
(setq suggest-key-bindings nil)
(put 'eval-expression 'disabled nil)
(put 'narrow-to-region 'disabled nil)
(put 'set-goal-column 'disabled nil)
;; Elisp archive searching
(autoload 'format-lisp-code-directory "lispdir" nil t)
(autoload 'lisp-dir-apropos "lispdir" nil t)
(autoload 'lisp-dir-retrieve "lispdir" nil t)
(autoload 'lisp-dir-verify "lispdir" nil t)
;; Font lock mode
(defun my-make-face (face colour &optional bold)
"Create a face from a colour and optionally make it bold"
(make-face face)
(copy-face 'default face)
(set-face-foreground face colour)
(if bold (make-face-bold face))
)
(if (eq window-system 'x)
(progn
(my-make-face 'blue "blue")
(my-make-face 'red "red")
(my-make-face 'green "dark green")
(setq font-lock-comment-face 'blue)
(setq font-lock-string-face 'bold)
(setq font-lock-type-face 'bold)
(setq font-lock-keyword-face 'bold)
(setq font-lock-function-name-face 'red)
(setq font-lock-doc-string-face 'green)
(add-hook 'find-file-hooks 'font-lock-auto-mode-select)
(setq baud-rate 1000000)
(global-set-key "\C-cmm" 'menu-bar-mode)
(global-set-key "\C-cms" 'scroll-bar-mode)
(global-set-key [backspace] 'backward-delete-char)
; (global-set-key [delete] 'delete-char)
(standard-display-european t)
(load-library "iso-transl")))
;; X11 or PC using direct screen writes
(if window-system
(progn
;; (global-set-key [M-f1] 'hilit-repaint-command)
;; (global-set-key [M-f2] [?\C-u M-f1])
(setq hilit-mode-enable-list
'(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode
scheme-mode)
hilit-auto-highlight nil
hilit-auto-rehighlight 'visible
hilit-inhibit-hooks nil
hilit-inhibit-rebinding t)
(require 'hilit19)
(require 'paren))
(setq baud-rate 2400) ; For slow serial connections
)
;; TTY type terminal
(if (and (not window-system)
(not (equal system-type 'ms-dos)))
(progn
(if first-time
(progn
(keyboard-translate ?\C-h ?\C-?)
(keyboard-translate ?\C-? ?\C-h)))))
;; Under UNIX
(if (not (equal system-type 'ms-dos))
(progn
(if first-time
(server-start))))
;; Add any face changes here
(add-hook 'term-setup-hook 'my-term-setup-hook)
(defun my-term-setup-hook ()
(if (eq window-system 'pc)
(progn
;; (set-face-background 'default "red")
)))
;; Restore the "desktop" - do this as late as possible
(if first-time
(progn
(desktop-load-default)
(desktop-read)))
;; Indicate that this file has been read at least once
(setq first-time nil)
;; No need to debug anything now
(setq debug-on-error nil)
;; All done
(message "All done, %s%s" (user-login-name) ".")
</programlisting>
</example>
</sect2>
<sect2>
<title>Extending the Range of Languages Emacs Understands</title>
<para>Now, this is all very well if you only want to program in
the languages already catered for in the
<filename>.emacs</filename> file (C, C++, Perl, Lisp and
Scheme), but what happens if a new language called
<quote>whizbang</quote> comes out, full of exciting
features?</para>
<para>The first thing to do is find out if whizbang comes with
any files that tell Emacs about the language. These usually
end in <filename>.el</filename>, short for <quote>Emacs
Lisp</quote>. For example, if whizbang is a FreeBSD port, we
can locate these files by doing</para>
<screen>&prompt.user; <userinput>find /usr/ports/lang/whizbang -name "*.el" -print</userinput>
</screen>
<para>and install them by copying them into the Emacs site Lisp
directory. On FreeBSD 2.1.0-RELEASE, this is
<filename>/usr/local/share/emacs/site-lisp</filename>.</para>
<para>So for example, if the output from the find command
was</para>
<screen>/usr/ports/lang/whizbang/work/misc/whizbang.el
</screen>
<para>we would do</para>
<screen>&prompt.root; <userinput>cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp</userinput>
</screen>
<para>Next, we need to decide what extension whizbang source
files have. Let's say for the sake of argument that they all
end in <filename>.wiz</filename>. We need to add an entry to
our <filename>.emacs</filename> file to make sure Emacs will
be able to use the information in
<filename>whizbang.el</filename>.</para>
<para>Find the <symbol>auto-mode-alist entry</symbol> in
<filename>.emacs</filename> and add a line for whizbang, such
as:</para>
<programlisting><lineannotation>…</>
("\\.lsp$" . lisp-mode)
("\\.wiz$" . whizbang-mode)
("\\.scm$" . scheme-mode)
<lineannotation>…</>
</programlisting>
<para>This means that Emacs will automatically go into
<function>whizbang-mode</function> when you edit a file ending
in <filename>.wiz</filename>.</para>
<para>Just below this, you'll find the
<symbol>font-lock-auto-mode-list</symbol> entry. Add
<function>whizbang-mode</function> to it like so:</para>
<programlisting>;; Auto font lock mode
(defvar font-lock-auto-mode-list
(list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode)
"List of modes to always start in font-lock-mode")
</programlisting>
<para>This means that Emacs will always enable
<function>font-lock-mode</function> (ie syntax highlighting)
when editing a <filename>.wiz</filename> file.</para>
<para>And that's all that's needed. If there's anything else
you want done automatically when you open up a
<filename>.wiz</filename> file, you can add a
<function>whizbang-mode hook</function> (see
<function>my-scheme-mode-hook</function> for a simple example
that adds <function>auto-indent</function>).</para>
</sect2>
</sect1>
<sect1>
<title>Further Reading</title>
<itemizedlist>
<listitem>
<para>Brian Harvey and Matthew Wright
<emphasis>Simply Scheme</emphasis>
MIT 1994.<!-- <br> -->
ISBN 0-262-08226-8</para>
</listitem>
<listitem>
<para>Randall Schwartz
<emphasis>Learning Perl</emphasis>
O'Reilly 1993<!-- <br> -->
ISBN 1-56592-042-2</para>
</listitem>
<listitem>
<para>Patrick Henry Winston and Berthold Klaus Paul Horn
<emphasis>Lisp (3rd Edition)</emphasis>
Addison-Wesley 1989<!-- <br> -->
ISBN 0-201-08319-1</para>
</listitem>
<listitem>
<para>Brian W. Kernighan and Rob Pike
<emphasis>The Unix Programming Environment</emphasis>
Prentice-Hall 1984<!-- <br> -->
ISBN 0-13-937681-X</para>
</listitem>
<listitem>
<para>Brian W. Kernighan and Dennis M. Ritchie
<emphasis>The C Programming Language (2nd Edition)</emphasis>
Prentice-Hall 1988<!-- <br> -->
ISBN 0-13-110362-8</para>
</listitem>
<listitem>
<para>Bjarne Stroustrup
<emphasis>The C++ Programming Language</emphasis>
Addison-Wesley 1991<!-- <br> -->
ISBN 0-201-53992-6</para>
</listitem>
<listitem>
<para>W. Richard Stevens
<emphasis>Advanced Programming in the Unix Environment</emphasis>
Addison-Wesley 1992<!-- <br> -->
ISBN 0-201-56317-7</para>
</listitem>
<listitem>
<para>W. Richard Stevens
<emphasis>Unix Network Programming</emphasis>
Prentice-Hall 1990<!-- <br> -->
ISBN 0-13-949876-1</para>
</listitem>
</itemizedlist>
</sect1>
</chapter>
<chapter id="secure-programming">
<title>Secure Programming</title>
<para>This chapter was written by Murray Stokely.</para>
<sect1><title>Synopsis</title>
<para>This chapter describes some of the security issues that
have plagued Unix programmers for decades and some of the new
tools available to help programmers avoid writing exploitable
code.</para>
</sect1>
<sect1 id="secure-philosophy"><title>Secure Design
Methodology</title>
<para>Writing secure applications takes a very scrutinous and
pessimistic outlook on life. Applications should be run with
the principle of <quote>least privilege</quote> so that no
process is ever running than more with the bare minimum access
that it needs to accomplish its function. Previously tested
code should be reused whenever possible to avoid common
mistakes that others may have already fixed.</para>
<para>One of the pitfalls of the Unix environment is how easy it
is to make assumptions about the sanity of the environment.
Applications should never trust user input (in all its forms),
system resources, inter-process communication, or the timing of
events. Unix processes do not execute synchronously so logical
operations are rarely atomic.</para>
</sect1>
<sect1><title>Buffer Overflows</title>
<para>Buffer Overflows have been around since the very
beginnings of the Von-Neuman <xref linkend="COD"> architecture.
They first gained widespread notoriety in 1988 with the Moorse
Internet worm. Unfortunately, the same basic attack remains
effective today. Of the 17 CERT security advisories of 1999, 10
of them were directly caused by buffer-overflow software bugs.
By far the most common type of buffer overflow attack is based
on corrupting the stack.</para>
<para>Most modern computer systems use a stack to pass arguments
to procedures and to store local variables. A stack is a last
in first out (LIFO) buffer in the high memory area of a process
image. When a program invokes a function a new "stack frame" is
created. This stack frame consists of the arguments passed to
the function as well as a dynamic amount of local variable
space. The "stack pointer" is a register that holds the current
location of the top of the stack. Since this value is
constantly changing as new values are pushed onto the top of the
stack, many implementations also provide a "frame pointer" that
is located near the beginning of a stack frame so that local
variables can more easily be addressed relative to this
value. <xref linkend="COD"> The return address for function
calls is also stored on the stack, and this is the cause of
stack-overflow exploits since overflowing a local variable in a
function can overwrite the return address of that function,
potentially allowing a malicious user to execute any code he or
she wants.</para>
<para>Although stack-based attacks are by far the most common,
it would also be possible to overrun the stack with a heap-based
(malloc/free) attack.</para>
<para>The C programming language does not perform automatic
bounds checking on arrays or pointers as many other languages
do. In addition, the standard C library is filled with a
handful of very dangerous functions.</para>
<informaltable>
<tgroup cols=2>
<tbody>
<row><entry><function>strcpy</function>(char *dest, const char
*src)</entry>
<entry><simpara>May overflow the dest buffer</simpara></entry>
</row>
<row><entry><function>strcat</function>(char *dest, const char
*src)</entry>
<entry><simpara>May overflow the dest buffer</simpara></entry>
</row>
<row><entry><function>getwd</function>(char *buf)</entry>
<entry><simpara>May overflow the buf buffer</simpara></entry>
</row>
<row><entry><function>gets</function>(char *s)</entry>
<entry><simpara>May overflow the s buffer</simpara></entry>
</row>
<row><entry><function>[vf]scanf</function>(const char *format,
...)</entry>
<entry><simpara>May overflow its arguments.</simpara></entry>
</row>
<row><entry><function>realpath</function>(char *path, char
resolved_path[])</entry>
<entry><simpara>May overflow the path buffer</simpara></entry>
</row>
<row><entry><function>[v]sprintf</function>(char *str, const char
*format, ...)</entry>
<entry><simpara>May overflow the str buffer.</simpara></entry>
</row>
</tbody>
</tgroup>
</informaltable>
<sect2><title>Example Buffer Overflow</title>
<para>The following example code contains a buffer overflow
designed to overwrite the return address and skip the
instruction immediately following the function call. (Inspired
by <xref linkend="Phrack">)</para>
<programlisting>
#include <sgmltag>stdio.h</sgmltag>
void manipulate(char *buffer) {
char newbuffer[80];
strcpy(newbuffer,buffer);
}
int main() {
char ch,buffer[4096];
int i=0;
while ((buffer[i++] = getchar()) != '\n') {};
i=1;
manipulate(buffer);
i=2;
printf("The value of i is : %d\n",i);
return 0;
}
</programlisting>
<para>Let us examine what the memory image of this process would
look like if we were to input 160 spaces into our little program
before hitting return.</para>
<para>[XXX figure here!]</para>
<para>Obviously more malicious input can be devised to execute
actual compiled instructions (such as exec(/bin/sh)).</para>
</sect2>
<sect2><title>Avoiding Buffer Overflows</title>
<para>The most straightforward solution to the problem of
stack-overflows is to always use length restricted memory and
string copy functions. <function>strncpy</function> and
<function>strncat</function> are part of the standard C library.
These functions accept a length value as a parameter which
should be no larger than the size of the destination buffer.
These functions will then copy up to `length' bytes from the
source to the destination. However there are a number of
problems with these functions. Neither function guarantees NUL
termination if the size of the input buffer is as large as the
destination. The length parameter is also used inconsistently
between strncpy and strncat so it is easy for programmers to get
confused as to their proper usage. There is also a significant
performance loss compared to <function>strcpy</function> when
copying a short string into a large buffer since
<function>strncpy</function> NUL fills up the the size
specified.</para>
<para>In OpenBSD, another memory copy implementation has been
created to get around these problem. The
<function>strlcpy</function> and <function>strlcat</function>
functions guarantee that they will always null terminate the
destination string when given a non-zero length argument. For
more information about these functions see <xref
linkend="OpenBSD">. The OpenBSD <function>strlcpy</function> and
<function>strlcat</function> instructions have been in FreeBSD
since 3.5.</para>
<sect3><title>Compiler based run-time bounds checking</title>
<para>Unfortunately there is still a very large assortment of
code in public use which blindly copies memory around without
using any of the bounded copy routines we just discussed.
Fortunately, there is another solution. Several compiler
add-ons and libraries exist to do Run-time bounds checking in
C/C++.</para>
<para>StackGuard is one such add-on that is implemented as a
small patch to the gcc code generator. From the StackGuard
website, http://immunix.org/stackguard.html :
<blockquote><para>"StackGuard detects and defeats stack
smashing attacks by protecting the return address on the stack
from being altered. StackGuard places a "canary" word next to
the return address when a function is called. If the canary
word has been altered when the function returns, then a stack
smashing attack has been attempted, and the program responds
by emitting an intruder alert into syslog, and then
halts."</para></blockquote>
<blockquote><para>"StackGuard is implemented as a small patch
to the gcc code generator, specifically the function_prolog()
and function_epilog() routines. function_prolog() has been
enhanced to lay down canaries on the stack when functions
start, and function_epilog() checks canary integrity when the
function exits. Any attempt at corrupting the return address
is thus detected before the function
returns."</para></blockquote>
</para>
<para>Recompiling your application with StackGuard is an
effective means of stopping most buffer-overflow attacks, but
it can still be compromised.</para>
</sect3>
<sect3><title>Library based run-time bounds checking</title>
<para>Compiler-based mechanisms are completely useless for
binary-only software for which you cannot recompile. For
these situations there are a number of libraries which
re-implement the unsafe functions of the C-library
(<function>strcpy</function>, <function>fscanf</function>,
<function>getwd</function>, etc..) and ensure that these
functions can never write past the stack pointer.</para>
<itemizedlist>
<listitem><simpara>libsafe</simpara></listitem>
<listitem><simpara>libverify</simpara></listitem>
<listitem><simpara>libparnoia</simpara></listitem>
</itemizedlist>
<para>Unfortunately these library-based defenses have a number
of shortcomings. These libraries only protect against a very
small set of security related issues and they neglect to fix
the actual problem. These defenses may fail if the
application was compiled with -fomit-frame-pointer. Also, the
LD_PRELOAD and LD_LIBRARY_PATH environment variables can be
overwritten/unset by the user.</para>
</sect3>
</sect2>
</sect1>
<sect1><title>SetUID issues</title>
<para>There are at least 6 different IDs associated with any
given process. Because of this you have to be very careful with
the access that your process has at any given time. In
particular, all seteuid applications should give up their
privileges as soon as it is no longer required.</para>
<para>The real user ID can only be changed by a superuser
process. The <application>login</application> program sets this
when a user initially logs in and it is seldom changed.</para>
<para>The effective user ID is set by the
<function>exec()</function> functions if a program has its
seteuid bit set. An application can call
<function>seteuid()</function> at any time to set the effective
user ID to either the real user ID or the saved set-user-ID.
When the effective user ID is set by <function>exec()</function>
functions, the previous value is saved in the saved set-user-ID.</para>
</sect1>
<sect1 id="chroot"><title>Limiting your program's environment</title>
<para>The traditional method of restricting access to a process
is with the <function>chroot()</function> system call. This
system call changes the root directory from which all other
paths are referenced for a process and any child processes. For
this call to succeed the process must have execute (search)
permission on the directory being referenced. The new
environment does not actually take affect until you
<function>chdir()</function> into your new environment. It
should also be noted that a process can easily break out of a
chroot environment if it has root privilege. This could be
accomplished by creating device nodes to read kernel memory,
attaching a debugger to a process outside of the jail, or in
many other creative ways.</para>
<para>The behavior of the <function>chroot()</function> system
call can be controlled somewhat with the
kern.chroot_allow_open_directories <command>sysctl</command>
variable. When this value is set to 0,
<function>chroot()</function> will fail with EPERM if there are
any directories open. If set to the default value of 1, then
<function>chroot()</function> will fail with EPERM if there are
any directories open and the process is already subject to a
<function>chroot()</function> call. For any other value, the
check for open directories will be bypassed completely.</para>
<sect2><title>FreeBSD's jail functionality</title>
<para>The concept of a Jail extends upon the
<function>chroot()</function> by limiting the powers of the
superuser to create a true `virtual server'. Once a prison is
setup all network communication must take place through the
specified IP address, and the power of "root privilege" in this
jail is severely constrained.</para>
<para>While in a prison, any tests of superuser power within the
kernel using the <function>suser()</function> call will fail.
However, some calls to <function>suser()</function> have been
changed to a new interface <function>suser_xxx()</function>.
This function is responsible for recognizing or denying access
to superuser power for imprisoned processes.</para>
<para>A superuser process within a jailed environment has the
power to : </para>
<itemizedlist>
<listitem><simpara>Manipulate credential with
<function>setuid</function>, <function>seteuid</function>,
<function>setgid</function>, <function>setegid</function>,
<function>setgroups</function>, <function>setreuid</function>,
<function>setregid</function>, <function>setlogin</function></simpara></listitem>
<listitem><simpara>Set resource limits with <function>setrlimit</function></simpara></listitem>
<listitem><simpara>Modify some sysctl nodes
(kern.hostname)</simpara></listitem>
<listitem><simpara><function>chroot()</function></simpara></listitem>
<listitem><simpara>Set flags on a vnode:
<function>chflags</function>,
<function>fchflags</function></simpara></listitem>
<listitem><simpara>Set attributes of a vnode such as file
permission, owner, group, size, access time, and modification
time.</simpara></listitem>
<listitem><simpara>Bind to privileged ports in the Internet
domain (ports < 1024)</simpara></listitem>
</itemizedlist>
<para><function>Jail</function> is a very useful tool for
running applications in a secure environment but it does have
some shortcomings. Currently, the IPC mechanisms have not been
converted to the <function>suser_xxx</function> so applications
such as MySQL can not be run within a jail. Superuser access
may have a very limited meaning within a jail, but there is
no way to specify exactly what "very limited" means.</para>
</sect2>
<sect2><title>POSIX.1e Process Capabilities</title>
<para>Posix has released a working draft that adds event
auditing, access control lists, fine grained privileges,
information labeling, and mandatory access control.</para>
<para>This is a work in progress and is the focus of the <ulink
url="http://www.trustedbsd.org">TrustedBSD</ulink> project. Some
of the initial work has been committed to FreeBSD-current
(cap_set_proc(3)).</para>
</sect2>
</sect1>
<sect1><title>Trust</title>
<para>An application should never assume that anything about the
users environment is sane. This includes (but is certainly not
limited to) : user input, signals, environment variables,
resources, IPC, mmaps, the file system working directory, file
descriptors, the # of open files, etc.</para>
<para>You should never assume that you can catch all forms of
invalid input that a user might supply. Instead, your
application should use positive filtering to only allow a
specific subset of inputs that you deem safe. Improper data
validation has been the cause of many exploits, especially with
CGI scripts on the world wide web. For filenames you need to be
extra careful about paths ("../", "/"), symbolic links, and
shell escape characters.</para>
<para>Perl has a really cool feature called "Taint" mode which
can be used to prevent scripts for using data derived outside
the program in an unsafe way. This mode will check command line
arguments, environment variables, locale information, the
results of certain syscalls (<function>readdir()</function>,
<function>readlink()</function>,
<function>getpwxxx()</function>, and all file input.</para>
</sect1>
<sect1><title>Race Conditions</title>
<para>A race condition is anomalous behavior caused by the
unexpected dependence on the relative timing of events. In
other words, a programmer incorrectly assumed that a particular
event would always happen before another.</para>
<para>Some of the common causes of race conditions are signals,
access checks, and file opens. Signals are asynchronous events
by nature so special care must be taken in dealing with them.
Checking access with <function>access(2)</function> then
<function>open(2)</function> is clearly non-atomic. Users can
move files in between the two calls. Instead, privileged
applications should <function>seteuid()</function> and then call
<function>open()</function> directly. Along the same lines, an
application should always set a proper umask before
<function>open()</function> to obviate the need for spurious
<function>chmod()</function> calls.</para>
</sect1>
</chapter>
</part>
<part id="kernel">
<title>Kernel</title>
<chapter id="kernelhistory">
<title>History of the Unix Kernel</title>
<para>Some history of the Unix/BSD kernel, system calls, how do
processes work, blocking, scheduling, threads (kernel),
context switching, signals, interrupts, modules, etc.</para>
<para></para>
</chapter>
</part>
<part id="memory">
<title>Memory and Virtual Memory</title>
<chapter id="virtualmemory">
<title>Virtual Memory</title>
<para>VM, paging, swapping, allocating memory, testing for
memory leaks, mmap, vnodes, etc.</para>
<para></para>
</chapter>
</part>
<part id="iosystem">
<title>I/O System</title>
<chapter id="ufs">
<title>UFS</title>
<para>UFS, FFS, Ext2FS, JFS, inodes, buffer cache, labeling,
locking, metadata, soft-updates, LFS, portalfs, procfs,
vnodes, memory sharing, memory objects, TLBs, caching</para>
</chapter>
</part>
<part id="ipc">
<title>Interprocess Communication</title>
<chapter id="signals">
<title>Signals</title>
<para>Signals, pipes, semaphores, message queues, shared memory,
ports, sockets, doors</para>
</chapter>
</part>
<part id="networking">
<title>Networking</title>
<chapter id="sockets">
<title>Sockets</title>
<para>Sockets, bpf, IP, TCP, UDP, ICMP, OSI, bridging,
firewalling, NAT, switching, etc</para>
</chapter>
</part>
<part id="networkfs">
<title>Network Filesystems</title>
<chapter id="afs">
<title>AFS</title>
<para>AFS, NFS, SANs etc]</para>
</chapter>
</part>
<part id="terminal">
<title>Terminal Handling</title>
<chapter id="syscons">
<title>Syscons</title>
<para>Syscons, tty, PCVT, serial console, screen savers,
etc</para>
</chapter>
</part>
<part id="sound">
<title>Sound</title>
<chapter id="oss">
<title>OSS</title>
<para>OSS, waveforms, etc</para>
</chapter>
</part>
<part id="devicedrivers">
<title>Device Drivers</title>
<chapter id="driverbasics">
<title>Writing FreeBSD Device Drivers</title>
<para>This chapter was written by Murray Stokely with selections from
a variety of sources including the intro(4) man page by Joerg
Wunsch.</para>
<sect1>
<title>Introduction</title>
<para>
This chapter provides a brief introduction to writing device
drivers for FreeBSD. A device in this context is a term used
mostly for hardware-related stuff that belongs to the system,
like disks, printers, or a graphics display with its keyboard.
A device driver is the software component of the operating
system that controls a specific device. There are also
so-called pseudo-devices where a device driver emulates the
behaviour of a device in software without any particular
underlying hardware. Device drivers can be compiled into the
system statically or loaded on demand through the dynamic
kernel linker facility `kld'.</para>
<para>Most devices in a Unix-like operating system are
accessed through device-nodes, sometimes also called special
files. These files are usually located under the directory
<filename>/dev</filename> in the file system hierarchy. Until
devfs is fully integrated into FreeBSD, each device node must
be created statically and independent of the existence of the
associated device driver. Most device nodes on the system are
created by running <command>MAKEDEV</command>.</para>
<para>Device drivers can roughly be broken down into three
categories; character (unbuffered), block (buffered), and
network drivers.</para>
</sect1>
<sect1>
<title>Dynamic Kernel Linker Facility - KLD</title>
<para>The kld interface allows system administrators to
dynamically add and remove functionality from a running
system. This allows device driver writers to load their new
changes into a running kernel without constantly rebooting to
test changes.</para>
<para>The kld interface is used through the following
administrator commands :
<itemizedlist>
<listitem><simpara><command>kldload</command> - loads a new kernel
module</simpara></listitem>
<listitem><simpara><command>kldunload</command> - unloads a kernel
module</simpara></listitem>
<listitem><simpara><command>kldstat</command> - lists the currently loadded
modules</simpara></listitem>
</itemizedlist>
</para>
<para>Skeleton Layout of a kernel module</para>
<programlisting>
/*
* KLD Skeleton
* Inspired by Andrew Reiter's Daemonnews article
*/
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
/*
* Load handler that deals with the loading and unloading of a KLD.
*/
static int
skel_loader(struct module *m, int what, void *arg)
{
int err = 0;
switch (what) {
case MOD_LOAD: /* kldload */
uprintf("Skeleton KLD loaded.\n");
break;
case MOD_UNLOAD:
uprintf("Skeleton KLD unloaded.\n");
break;
default:
err = EINVAL;
break;
}
return(err);
}
/* Declare this module to the rest of the kernel */
DECLARE_MODULE(skeleton, skel_loader, SI_SUB_KLD, SI_ORDER_ANY);
</programlisting>
<sect2>
<title>Makefile</title>
<para>FreeBSD provides a makefile include that you can use
to quickly compile your kernel addition.</para>
<programlisting>
SRCS=skeleton.c
KMOD=skeleton
.include <bsd.kmod.mk>
</programlisting>
<para>Simply running <command>make</command> with
this makefile will create a file
<filename>skeleton.ko</filename> that can be loaded into
your system by typing :
<screen>
&prompt.root kldload -v ./skeleton.ko
</screen>
</para>
</sect2>
</sect1>
<sect1>
<title>Accessing a device driver</title>
<para>Unix provides a common set of system calls for user
applications to use. The upper layers of the kernel dispatch
these calls to the corresponding device driver when a user
accesses a device node. The <command>/dev/MAKEDEV</command>
script makes most of the device nodes for your system but if
you are doing your own driver development it may be necessary
to create your own device nodes with <command>mknod</command>
</para>
<sect2>
<title>Creating static device nodes</title>
<para>The <command>mknod</command> command requires four
arguments to create a device node. You must specify the
name of this device node, the type of device, the major number
of the device, and the minor number of the device.</para>
</sect2>
<sect2>
<title>Dynamic device nodes</title>
<para>The device filesystem, or devfs, provides access to the
kernel's device namespace in the global filesystem namespace.
This eliminates the problems of potentially having a device
driver without a static device node, or a device node without
an installed device driver. Unfortunately, devfs is still a
work in progress.</para>
</sect2>
</sect1>
<sect1>
<title>Character Devices</title>
<para>A character device driver is one that transfers data
directly to and from a user process. This is the most common
type of device driver and there are plenty of simple examples
in the source tree.</para>
<para>This simple example pseudo-device remembers whatever values you write
to it and can then supply them back to you when you read from
it.</para>
<programlisting>
/*
* Simple `echo' pseudo-device KLD
*
* Murray Stokely
*/
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
#include <sys/conf.h> /* cdevsw struct */
#include <sys/uio.h> /* uio struct */
#include <sys/malloc.h>
#define BUFFERSIZE 256
/* Function prototypes */
d_open_t echo_open;
d_close_t echo_close;
d_read_t echo_read;
d_write_t echo_write;
/* Character device entry points */
static struct cdevsw echo_cdevsw = {
echo_open,
echo_close,
echo_read,
echo_write,
noioctl,
nopoll,
nommap,
nostrategy,
"echo",
33, /* reserved for lkms - /usr/src/sys/conf/majors */
nodump,
nopsize,
D_TTY,
-1
};
typedef struct s_echo {
char msg[BUFFERSIZE];
int len;
} t_echo;
/* vars */
static dev_t sdev;
static int len;
static int count;
static t_echo *echomsg;
MALLOC_DECLARE(M_ECHOBUF);
MALLOC_DEFINE(M_ECHOBUF, "echobuffer", "buffer for echo module");
/*
* This function acts is called by the kld[un]load(2) system calls to
* determine what actions to take when a module is loaded or unloaded.
*/
static int
echo_loader(struct module *m, int what, void *arg)
{
int err = 0;
switch (what) {
case MOD_LOAD: /* kldload */
sdev = make_dev(<literal>&</literal>echo_cdevsw,
0,
UID_ROOT,
GID_WHEEL,
0600,
"echo");
/* kmalloc memory for use by this driver */
/* malloc(256,M_ECHOBUF,M_WAITOK); */
MALLOC(echomsg, t_echo *, sizeof(t_echo), M_ECHOBUF, M_WAITOK);
printf("Echo device loaded.\n");
break;
case MOD_UNLOAD:
destroy_dev(sdev);
FREE(echomsg,M_ECHOBUF);
printf("Echo device unloaded.\n");
break;
default:
err = EINVAL;
break;
}
return(err);
}
int
echo_open(dev_t dev, int oflags, int devtype, struct proc *p)
{
int err = 0;
uprintf("Opened device \"echo\" successfully.\n");
return(err);
}
int
echo_close(dev_t dev, int fflag, int devtype, struct proc *p)
{
uprintf("Closing device \"echo.\"\n");
return(0);
}
/*
* The read function just takes the buf that was saved via
* echo_write() and returns it to userland for accessing.
* uio(9)
*/
int
echo_read(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
int amt;
/* How big is this read operation? Either as big as the user wants,
or as big as the remaining data */
amt = MIN(uio->uio_resid, (echomsg->len - uio->uio_offset > 0) ? echomsg->len - uio->uio_offset : 0);
if ((err = uiomove(echomsg->msg + uio->uio_offset,amt,uio)) != 0) {
uprintf("uiomove failed!\n");
}
return err;
}
/*
* echo_write takes in a character string and saves it
* to buf for later accessing.
*/
int
echo_write(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
/* Copy the string in from user memory to kernel memory */
err = copyin(uio->uio_iov->iov_base, echomsg->msg, MIN(uio->uio_iov->iov_len,BUFFERSIZE));
/* Now we need to null terminate */
*(echomsg->msg + MIN(uio->uio_iov->iov_len,BUFFERSIZE)) = 0;
/* Record the length */
echomsg->len = MIN(uio->uio_iov->iov_len,BUFFERSIZE);
if (err != 0) {
uprintf("Write failed: bad address!\n");
}
count++;
return(err);
}
DEV_MODULE(echo,echo_loader,NULL);
</programlisting>
<para>To install this driver you will first need to make a node on
your filesystem with a command such as : </para>
<screen>
&prompt.root mknod /dev/echo c 33 0
</screen>
<para>With this driver loaded you should now be able to type something
like :</para>
<screen>
&prompt.root echo -n "Test Data" > /dev/echo
&prompt.root cat /dev/echo
Test Data
</screen>
<para>Real hardware devices in the next chapter..</para>
<para>Additional Resources
<itemizedlist>
<listitem><simpara><ulink
url="http://www.daemonnews.org/200010/blueprints.html">Dynamic
Kernel Linker (KLD) Facility Programming Tutorial</ulink> -
<ulink url="http://www.daemonnews.org">Daemonnews</ulink> October 2000</simpara></listitem>
<listitem><simpara><ulink
url="http://www.daemonnews.org/200007/newbus-intro.html">How
to Write Kernel Drivers with NEWBUS</ulink> - <ulink
url="http://www.daemonnews.org">Daemonnews</ulink> July
2000</simpara></listitem>
</itemizedlist>
</para>
</sect1>
<sect1>
<title>Block Devices</title>
<para>A block device driver transfers data to and from the
operating system's buffer cache. They are solely intended to
layer a file system on top of them. For this reason they are
normally implemented for disks and disk-like devices only.</para>
<para>Example test data generator ... </para>
<para>Example ramdisk device ... </para>
<para>Real hardware devices in the next chapter..</para>
</sect1>
<sect1>
<title>Network Drivers</title>
<para>Drivers for network devices do not use device nodes in
ord to be accessed. Their selection is based on other
decisions made inside the kernel and instead of calling
open(), use of a network device is generally introduced by
using the system call socket(2).</para>
<para>man ifnet(), loopback device, Bill Pauls drivers, etc..</para>
</sect1>
</chapter>
<chapter id="pci">
<title>PCI Devices</title>
<para>This chapter will talk about the FreeBSD mechanisms for
writing a device driver for a device on a PCI bus.</para>
<sect1><title>Probe and Attach</title>
<para>Information here about how the PCI bus code iterates
through the unattached devices and see if a newly loaded kld
will attach to any of them.</para>
<programlisting>
/*
* Simple KLD to play with the PCI functions.
*
* Murray Stokely
*/
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
#include <sys/conf.h> /* cdevsw struct */
#include <sys/uio.h> /* uio struct */
#include <sys/malloc.h>
#include <sys/bus.h> /* structs, prototypes for pci bus stuff */
#include <pci/pcivar.h> /* For get_pci macros! */
/* Function prototypes */
d_open_t mypci_open;
d_close_t mypci_close;
d_read_t mypci_read;
d_write_t mypci_write;
/* Character device entry points */
static struct cdevsw mypci_cdevsw = {
mypci_open,
mypci_close,
mypci_read,
mypci_write,
noioctl,
nopoll,
nommap,
nostrategy,
"mypci",
36, /* reserved for lkms - /usr/src/sys/conf/majors */
nodump,
nopsize,
D_TTY,
-1
};
/* vars */
static dev_t sdev;
/* We're more interested in probe/attach than with
open/close/read/write at this point */
int
mypci_open(dev_t dev, int oflags, int devtype, struct proc *p)
{
int err = 0;
uprintf("Opened device \"mypci\" successfully.\n");
return(err);
}
int
mypci_close(dev_t dev, int fflag, int devtype, struct proc *p)
{
int err=0;
uprintf("Closing device \"mypci.\"\n");
return(err);
}
int
mypci_read(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
uprintf("mypci read!\n");
return err;
}
int
mypci_write(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
uprintf("mypci write!\n");
return(err);
}
/* PCI Support Functions */
/*
* Return identification string if this is device is ours.
*/
static int
mypci_probe(device_t dev)
{
uprintf("MyPCI Probe\n"
"Vendor ID : 0x%x\n"
"Device ID : 0x%x\n",pci_get_vendor(dev),pci_get_device(dev));
if (pci_get_vendor(dev) == 0x11c1) {
uprintf("We've got the Winmodem, probe successful!\n");
return 0;
}
return ENXIO;
}
/* Attach function is only called if the probe is successful */
static int
mypci_attach(device_t dev)
{
uprintf("MyPCI Attach for : deviceID : 0x%x\n",pci_get_vendor(dev));
sdev = make_dev(<literal>&</literal>mypci_cdevsw,
0,
UID_ROOT,
GID_WHEEL,
0600,
"mypci");
uprintf("Mypci device loaded.\n");
return ENXIO;
}
/* Detach device. */
static int
mypci_detach(device_t dev)
{
uprintf("Mypci detach!\n");
return 0;
}
/* Called during system shutdown after sync. */
static int
mypci_shutdown(device_t dev)
{
uprintf("Mypci shutdown!\n");
return 0;
}
/*
* Device suspend routine.
*/
static int
mypci_suspend(device_t dev)
{
uprintf("Mypci suspend!\n");
return 0;
}
/*
* Device resume routine.
*/
static int
mypci_resume(device_t dev)
{
uprintf("Mypci resume!\n");
return 0;
}
static device_method_t mypci_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, mypci_probe),
DEVMETHOD(device_attach, mypci_attach),
DEVMETHOD(device_detach, mypci_detach),
DEVMETHOD(device_shutdown, mypci_shutdown),
DEVMETHOD(device_suspend, mypci_suspend),
DEVMETHOD(device_resume, mypci_resume),
{ 0, 0 }
};
static driver_t mypci_driver = {
"mypci",
mypci_methods,
0,
/* sizeof(struct mypci_softc), */
};
static devclass_t mypci_devclass;
DRIVER_MODULE(mypci, pci, mypci_driver, mypci_devclass, 0, 0);
</programlisting>
<para>Additional Resources
<itemizedlist>
<listitem><simpara><ulink
url="http://www.pcisig.org">PCI Special Interest
Group</ulink></simpara></listitem>
<listitem><simpara>PCI System Architecture, Fourth Edition by
Tom Shanley, et al.</simpara></listitem>
</itemizedlist>
</para>
</sect1>
</chapter>
<chapter id="usb">
<title>USB Devices</title>
<para>This chapter will talk about the FreeBSD mechanisms for
writing a device driver for a device on a USB bus.</para>
</chapter>
<chapter id="newbus">
<title>NewBus</title>
<para>This chapter will talk about the FreeBSD NewBus
architecture.</para>
</chapter>
</part>
<part id="architectures">
<title>Architectures</title>
<chapter id="ia32">
<title>IA-32</title>
<para>Talk about the architectural specifics of FreeBSD/x86.</para>
</chapter>
<chapter id="alpha">
<title>Alpha</title>
<para>Talk about the architectural specifics of
FreeBSD/alpha.</para>
<para>Explanation of allignment errors, how to fix, how to
ignore.</para>
<para>Example assembly language code for FreeBSD/alpha.</para>
</chapter>
<chapter id="ia64">
<title>IA-64</title>
<para>Talk about the architectural specifics of
FreeBSD/ia64.</para>
</chapter>
</part>
<part id="debuggingpart">
<title>Debugging</title>
<chapter id="truss">
<title>Truss</title>
<para>various descriptions on how to debug certain aspects of
the system using truss, ktrace, gdb, kgdb, etc</para>
</chapter>
</part>
<part id="compatibility">
<title>Compatibility Layers</title>
<chapter id="linux">
<title>Linux</title>
<para>Linux, SVR4, etc</para>
</chapter>
</part>
<part id="appendices">
<title>Appendices</title>
<bibliography>
<biblioentry id="COD" xreflabel="1">
<authorgroup>
<author>
<firstname>Dave</firstname>
<othername role="MI">A</othername>
<surname>Patterson</surname>
</author>
<author>
<firstname>John</firstname>
<othername role="MI">L</othername>
<surname>Hennessy</surname>
</author>
</authorgroup>
<copyright><year>1998</year><holder>Morgan Kaufmann Publishers,
Inc.</holder></copyright>
<isbn>1-55860-428-6</isbn>
<publisher>
<publishername>Morgan Kaufmann Publishers, Inc.</publishername>
</publisher>
<title>Computer Organization and Design</title>
<subtitle>The Hardware / Software Interface</subtitle>
<pagenums>1-2</pagenums>
</biblioentry>
<biblioentry xreflabel="2">
<authorgroup>
<author>
<firstname>W.</firstname>
<othername role="Middle">Richard</othername>
<surname>Stevens</surname>
</author>
</authorgroup>
<copyright><year>1993</year><holder>Addison Wesley Longman,
Inc.</holder></copyright>
<isbn>0-201-56317-7</isbn>
<publisher>
<publishername>Addison Wesley Longman, Inc.</publishername>
</publisher>
<title>Advanced Programming in the Unix Environment</title>
<pagenums>1-2</pagenums>
</biblioentry>
<biblioentry xreflabel="3">
<authorgroup>
<author>
<firstname>Marshall</firstname>
<othername role="Middle">Kirk</othername>
<surname>McKusick</surname>
</author>
<author>
<firstname>Keith</firstname>
<surname>Bostic</surname>
</author>
<author>
<firstname>Michael</firstname>
<othername role="MI">J</othername>
<surname>Karels</surname>
</author>
<author>
<firstname>John</firstname>
<othername role="MI">S</othername>
<surname>Quarterman</surname>
</author>
</authorgroup>
<copyright><year>1996</year><holder>Addison-Wesley Publishing Company,
Inc.</holder></copyright>
<isbn>0-201-54979-4</isbn>
<publisher>
<publishername>Addison-Wesley Publishing Company, Inc.</publishername>
</publisher>
<title>The Design and Implementation of the 4.4 BSD Operating System</title>
<pagenums>1-2</pagenums>
</biblioentry>
<biblioentry id="Phrack" xreflabel="4">
<authorgroup>
<author>
<firstname>Aleph</firstname>
<surname>One</surname>
</author>
</authorgroup>
<title>Phrack 49; "Smashing the Stack for Fun and Profit"</title>
</biblioentry>
<biblioentry id="StackGuard" xreflabel="5">
<authorgroup>
<author>
<firstname>Chrispin</firstname>
<surname>Cowan</surname>
</author>
<author>
<firstname>Calton</firstname>
<surname>Pu</surname>
</author>
<author>
<firstname>Dave</firstname>
<surname>Maier</surname>
</author>
</authorgroup>
<title>StackGuard; Automatic Adaptive Detection and Prevention of
Buffer-Overflow Attacks</title>
</biblioentry>
<biblioentry id="OpenBSD" xreflabel="6">
<authorgroup>
<author>
<firstname>Todd</firstname>
<surname>Miller</surname>
</author>
<author>
<firstname>Theo</firstname>
<surname>de Raadt</surname>
</author>
</authorgroup>
<title>strlcpy and strlcat -- consistent, safe string copy and
concatenation.</title>
</biblioentry>
</bibliography>
</part>
</book>
|