1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
|
/* sort - sort lines of text (with all kinds of options).
Copyright (C) 1988, 1991-2010 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written December 1988 by Mike Haertel.
The author may be reached (Email) at the address mike@gnu.ai.mit.edu,
or (US mail) as Mike Haertel c/o Free Software Foundation.
Ørn E. Hansen added NLS support in 1997. */
#include <config.h>
#include <getopt.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include "system.h"
#include "argmatch.h"
#include "error.h"
#include "filevercmp.h"
#include "hard-locale.h"
#include "hash.h"
#include "heap.h"
#include "ignore-value.h"
#include "md5.h"
#include "mbswidth.h"
#include "nproc.h"
#include "physmem.h"
#include "posixver.h"
#include "quote.h"
#include "quotearg.h"
#include "randread.h"
#include "readtokens0.h"
#include "stdio--.h"
#include "stdlib--.h"
#include "strnumcmp.h"
#include "xmemcoll.h"
#include "xmemxfrm.h"
#include "xnanosleep.h"
#include "xstrtol.h"
#if HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif
#ifndef RLIMIT_DATA
struct rlimit { size_t rlim_cur; };
# define getrlimit(Resource, Rlp) (-1)
#endif
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "sort"
#define AUTHORS \
proper_name ("Mike Haertel"), \
proper_name ("Paul Eggert")
#if HAVE_LANGINFO_CODESET
# include <langinfo.h>
#endif
/* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
present. */
#ifndef SA_NOCLDSTOP
# define SA_NOCLDSTOP 0
/* No sigprocmask. Always 'return' zero. */
# define sigprocmask(How, Set, Oset) (0)
# define sigset_t int
# if ! HAVE_SIGINTERRUPT
# define siginterrupt(sig, flag) /* empty */
# endif
#endif
#if !defined OPEN_MAX && defined NR_OPEN
# define OPEN_MAX NR_OPEN
#endif
#if !defined OPEN_MAX
# define OPEN_MAX 20
#endif
#define UCHAR_LIM (UCHAR_MAX + 1)
#ifndef DEFAULT_TMPDIR
# define DEFAULT_TMPDIR "/tmp"
#endif
/* Maximum number of lines to merge every time a NODE is taken from
the MERGE_QUEUE. Node is at LEVEL in the binary merge tree,
and is responsible for merging TOTAL lines. */
#define MAX_MERGE(total, level) ((total) / ((2 << level) * (2 << level)) + 1)
/* Heuristic value for the number of lines for which it is worth
creating a subthread, during an internal merge sort, on a machine
that has processors galore. Currently this number is just a guess.
This value must be at least 4. We don't know of any machine where
this number has any practical effect. */
enum { SUBTHREAD_LINES_HEURISTIC = 4 };
/* Exit statuses. */
enum
{
/* POSIX says to exit with status 1 if invoked with -c and the
input is not properly sorted. */
SORT_OUT_OF_ORDER = 1,
/* POSIX says any other irregular exit must exit with a status
code greater than 1. */
SORT_FAILURE = 2
};
enum
{
/* The number of times we should try to fork a compression process
(we retry if the fork call fails). We don't _need_ to compress
temp files, this is just to reduce disk access, so this number
can be small. Each retry doubles in duration. */
MAX_FORK_TRIES_COMPRESS = 4,
/* The number of times we should try to fork a decompression process.
If we can't fork a decompression process, we can't sort, so this
number should be big. Each retry doubles in duration. */
MAX_FORK_TRIES_DECOMPRESS = 9
};
enum
{
/* Level of the end-of-merge node, one level above the root. */
MERGE_END = 0,
/* Level of the root node in merge tree. */
MERGE_ROOT = 1
};
/* The representation of the decimal point in the current locale. */
static int decimal_point;
/* Thousands separator; if -1, then there isn't one. */
static int thousands_sep;
/* Nonzero if the corresponding locales are hard. */
static bool hard_LC_COLLATE;
#if HAVE_NL_LANGINFO
static bool hard_LC_TIME;
#endif
#define NONZERO(x) ((x) != 0)
/* The kind of blanks for '-b' to skip in various options. */
enum blanktype { bl_start, bl_end, bl_both };
/* The character marking end of line. Default to \n. */
static char eolchar = '\n';
/* Lines are held in core as counted strings. */
struct line
{
char *text; /* Text of the line. */
size_t length; /* Length including final newline. */
char *keybeg; /* Start of first key. */
char *keylim; /* Limit of first key. */
};
/* Input buffers. */
struct buffer
{
char *buf; /* Dynamically allocated buffer,
partitioned into 3 regions:
- input data;
- unused area;
- an array of lines, in reverse order. */
size_t used; /* Number of bytes used for input data. */
size_t nlines; /* Number of lines in the line array. */
size_t alloc; /* Number of bytes allocated. */
size_t left; /* Number of bytes left from previous reads. */
size_t line_bytes; /* Number of bytes to reserve for each line. */
bool eof; /* An EOF has been read. */
};
struct keyfield
{
size_t sword; /* Zero-origin 'word' to start at. */
size_t schar; /* Additional characters to skip. */
size_t eword; /* Zero-origin last 'word' of key. */
size_t echar; /* Additional characters in field. */
bool const *ignore; /* Boolean array of characters to ignore. */
char const *translate; /* Translation applied to characters. */
bool skipsblanks; /* Skip leading blanks when finding start. */
bool skipeblanks; /* Skip leading blanks when finding end. */
bool numeric; /* Flag for numeric comparison. Handle
strings of digits with optional decimal
point, but no exponential notation. */
bool random; /* Sort by random hash of key. */
bool general_numeric; /* Flag for general, numeric comparison.
Handle numbers in exponential notation. */
bool human_numeric; /* Flag for sorting by human readable
units with either SI xor IEC prefixes. */
int iec_present; /* Flag for checking for mixed SI and IEC. */
bool month; /* Flag for comparison by month name. */
bool reverse; /* Reverse the sense of comparison. */
bool version; /* sort by version number */
bool obsolete_used; /* obsolescent key option format is used. */
struct keyfield *next; /* Next keyfield to try. */
};
struct month
{
char const *name;
int val;
};
/* Binary merge tree node. */
struct merge_node
{
struct line *lo; /* Lines to merge from LO child node. */
struct line *hi; /* Lines to merge from HI child ndoe. */
struct line *end_lo; /* End of available lines from LO. */
struct line *end_hi; /* End of available lines from HI. */
struct line **dest; /* Pointer to destination of merge. */
size_t nlo; /* Total Lines remaining from LO. */
size_t nhi; /* Total lines remaining from HI. */
size_t level; /* Level in merge tree. */
struct merge_node *parent; /* Parent node. */
bool queued; /* Node is already in heap. */
pthread_spinlock_t *lock; /* Lock for node operations. */
};
/* Priority queue of merge nodes. */
struct merge_node_queue
{
struct heap *priority_queue; /* Priority queue of merge tree nodes. */
pthread_mutex_t mutex; /* Lock for queue operations. */
pthread_cond_t cond; /* Conditional wait for empty queue to populate
when popping. */
};
/* FIXME: None of these tables work with multibyte character sets.
Also, there are many other bugs when handling multibyte characters.
One way to fix this is to rewrite `sort' to use wide characters
internally, but doing this with good performance is a bit
tricky. */
/* Table of blanks. */
static bool blanks[UCHAR_LIM];
/* Table of non-printing characters. */
static bool nonprinting[UCHAR_LIM];
/* Table of non-dictionary characters (not letters, digits, or blanks). */
static bool nondictionary[UCHAR_LIM];
/* Translation table folding lower case to upper. */
static unsigned char fold_toupper[UCHAR_LIM];
#define MONTHS_PER_YEAR 12
/* Table mapping month names to integers.
Alphabetic order allows binary search. */
static struct month monthtab[] =
{
{"APR", 4},
{"AUG", 8},
{"DEC", 12},
{"FEB", 2},
{"JAN", 1},
{"JUL", 7},
{"JUN", 6},
{"MAR", 3},
{"MAY", 5},
{"NOV", 11},
{"OCT", 10},
{"SEP", 9}
};
/* During the merge phase, the number of files to merge at once. */
#define NMERGE_DEFAULT 16
/* Minimum size for a merge or check buffer. */
#define MIN_MERGE_BUFFER_SIZE (2 + sizeof (struct line))
/* Minimum sort size; the code might not work with smaller sizes. */
#define MIN_SORT_SIZE (nmerge * MIN_MERGE_BUFFER_SIZE)
/* The number of bytes needed for a merge or check buffer, which can
function relatively efficiently even if it holds only one line. If
a longer line is seen, this value is increased. */
static size_t merge_buffer_size = MAX (MIN_MERGE_BUFFER_SIZE, 256 * 1024);
/* The approximate maximum number of bytes of main memory to use, as
specified by the user. Zero if the user has not specified a size. */
static size_t sort_size;
/* The guessed size for non-regular files. */
#define INPUT_FILE_SIZE_GUESS (1024 * 1024)
/* Array of directory names in which any temporary files are to be created. */
static char const **temp_dirs;
/* Number of temporary directory names used. */
static size_t temp_dir_count;
/* Number of allocated slots in temp_dirs. */
static size_t temp_dir_alloc;
/* Flag to reverse the order of all comparisons. */
static bool reverse;
/* Flag for stable sort. This turns off the last ditch bytewise
comparison of lines, and instead leaves lines in the same order
they were read if all keys compare equal. */
static bool stable;
/* If TAB has this value, blanks separate fields. */
enum { TAB_DEFAULT = CHAR_MAX + 1 };
/* Tab character separating fields. If TAB_DEFAULT, then fields are
separated by the empty string between a non-blank character and a blank
character. */
static int tab = TAB_DEFAULT;
/* Flag to remove consecutive duplicate lines from the output.
Only the last of a sequence of equal lines will be output. */
static bool unique;
/* Nonzero if any of the input files are the standard input. */
static bool have_read_stdin;
/* List of key field comparisons to be tried. */
static struct keyfield *keylist;
/* Program used to (de)compress temp files. Must accept -d. */
static char const *compress_program;
/* Annotate the output with extra info to aid the user. */
static bool debug;
/* Maximum number of files to merge in one go. If more than this
number are present, temp files will be used. */
static unsigned int nmerge = NMERGE_DEFAULT;
/* Report MESSAGE for FILE, then clean up and exit.
If FILE is null, it represents standard output. */
static void die (char const *, char const *) ATTRIBUTE_NORETURN;
static void
die (char const *message, char const *file)
{
error (0, errno, "%s: %s", message, file ? file : _("standard output"));
exit (SORT_FAILURE);
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
else
{
printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
or: %s [OPTION]... --files0-from=F\n\
"),
program_name, program_name);
fputs (_("\
Write sorted concatenation of all FILE(s) to standard output.\n\
\n\
"), stdout);
fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
fputs (_("\
Ordering options:\n\
\n\
"), stdout);
fputs (_("\
-b, --ignore-leading-blanks ignore leading blanks\n\
-d, --dictionary-order consider only blanks and alphanumeric characters\n\
-f, --ignore-case fold lower case to upper case characters\n\
"), stdout);
fputs (_("\
-g, --general-numeric-sort compare according to general numerical value\n\
-i, --ignore-nonprinting consider only printable characters\n\
-M, --month-sort compare (unknown) < `JAN' < ... < `DEC'\n\
"), stdout);
fputs (_("\
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)\n\
"), stdout);
fputs (_("\
-n, --numeric-sort compare according to string numerical value\n\
-R, --random-sort sort by random hash of keys\n\
--random-source=FILE get random bytes from FILE\n\
-r, --reverse reverse the result of comparisons\n\
"), stdout);
fputs (_("\
--sort=WORD sort according to WORD:\n\
general-numeric -g, human-numeric -h, month -M,\n\
numeric -n, random -R, version -V\n\
-V, --version-sort natural sort of (version) numbers within text\n\
\n\
"), stdout);
fputs (_("\
Other options:\n\
\n\
"), stdout);
fputs (_("\
--batch-size=NMERGE merge at most NMERGE inputs at once;\n\
for more use temp files\n\
"), stdout);
fputs (_("\
-c, --check, --check=diagnose-first check for sorted input; do not sort\n\
-C, --check=quiet, --check=silent like -c, but do not report first bad line\n\
--compress-program=PROG compress temporaries with PROG;\n\
decompress them with PROG -d\n\
"), stdout);
fputs (_("\
--debug annotate the part of the line used to sort,\n\
and warn about questionable usage to stderr\n\
--files0-from=F read input from the files specified by\n\
NUL-terminated names in file F;\n\
If F is - then read names from standard input\n\
"), stdout);
fputs (_("\
-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2\n\
(default end of line). See POS syntax below\n\
-m, --merge merge already sorted files; do not sort\n\
"), stdout);
fputs (_("\
-o, --output=FILE write result to FILE instead of standard output\n\
-s, --stable stabilize sort by disabling last-resort comparison\n\
-S, --buffer-size=SIZE use SIZE for main memory buffer\n\
"), stdout);
printf (_("\
-t, --field-separator=SEP use SEP instead of non-blank to blank transition\n\
-T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or %s;\n\
multiple options specify multiple directories\n\
--parallel=N limit the number of sorts run concurrently to N\n\
-u, --unique with -c, check for strict ordering;\n\
without -c, output only the first of an equal run\n\
"), DEFAULT_TMPDIR);
fputs (_("\
-z, --zero-terminated end lines with 0 byte, not newline\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
POS is F[.C][OPTS], where F is the field number and C the character position\n\
in the field; both are origin 1. If neither -t nor -b is in effect, characters\n\
in a field are counted from the beginning of the preceding whitespace. OPTS is\n\
one or more single-letter ordering options, which override global ordering\n\
options for that key. If no key is given, use the entire line as the key.\n\
\n\
SIZE may be followed by the following multiplicative suffixes:\n\
"), stdout);
fputs (_("\
% 1% of memory, b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y.\n\
\n\
With no FILE, or when FILE is -, read standard input.\n\
\n\
*** WARNING ***\n\
The locale specified by the environment affects sort order.\n\
Set LC_ALL=C to get the traditional sort order that uses\n\
native byte values.\n\
"), stdout );
emit_ancillary_info ();
}
exit (status);
}
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
CHECK_OPTION = CHAR_MAX + 1,
COMPRESS_PROGRAM_OPTION,
DEBUG_PROGRAM_OPTION,
FILES0_FROM_OPTION,
NMERGE_OPTION,
RANDOM_SOURCE_OPTION,
SORT_OPTION,
PARALLEL_OPTION
};
static char const short_options[] = "-bcCdfghik:mMno:rRsS:t:T:uVy:z";
static struct option const long_options[] =
{
{"ignore-leading-blanks", no_argument, NULL, 'b'},
{"check", optional_argument, NULL, CHECK_OPTION},
{"compress-program", required_argument, NULL, COMPRESS_PROGRAM_OPTION},
{"debug", no_argument, NULL, DEBUG_PROGRAM_OPTION},
{"dictionary-order", no_argument, NULL, 'd'},
{"ignore-case", no_argument, NULL, 'f'},
{"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
{"general-numeric-sort", no_argument, NULL, 'g'},
{"ignore-nonprinting", no_argument, NULL, 'i'},
{"key", required_argument, NULL, 'k'},
{"merge", no_argument, NULL, 'm'},
{"month-sort", no_argument, NULL, 'M'},
{"numeric-sort", no_argument, NULL, 'n'},
{"human-numeric-sort", no_argument, NULL, 'h'},
{"version-sort", no_argument, NULL, 'V'},
{"random-sort", no_argument, NULL, 'R'},
{"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
{"sort", required_argument, NULL, SORT_OPTION},
{"output", required_argument, NULL, 'o'},
{"reverse", no_argument, NULL, 'r'},
{"stable", no_argument, NULL, 's'},
{"batch-size", required_argument, NULL, NMERGE_OPTION},
{"buffer-size", required_argument, NULL, 'S'},
{"field-separator", required_argument, NULL, 't'},
{"temporary-directory", required_argument, NULL, 'T'},
{"unique", no_argument, NULL, 'u'},
{"zero-terminated", no_argument, NULL, 'z'},
{"parallel", required_argument, NULL, PARALLEL_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0},
};
#define CHECK_TABLE \
_ct_("quiet", 'C') \
_ct_("silent", 'C') \
_ct_("diagnose-first", 'c')
static char const *const check_args[] =
{
#define _ct_(_s, _c) _s,
CHECK_TABLE NULL
#undef _ct_
};
static char const check_types[] =
{
#define _ct_(_s, _c) _c,
CHECK_TABLE
#undef _ct_
};
#define SORT_TABLE \
_st_("general-numeric", 'g') \
_st_("human-numeric", 'h') \
_st_("month", 'M') \
_st_("numeric", 'n') \
_st_("random", 'R') \
_st_("version", 'V')
static char const *const sort_args[] =
{
#define _st_(_s, _c) _s,
SORT_TABLE NULL
#undef _st_
};
static char const sort_types[] =
{
#define _st_(_s, _c) _c,
SORT_TABLE
#undef _st_
};
/* The set of signals that are caught. */
static sigset_t caught_signals;
/* Critical section status. */
struct cs_status
{
bool valid;
sigset_t sigs;
};
/* Enter a critical section. */
static struct cs_status
cs_enter (void)
{
struct cs_status status;
status.valid = (sigprocmask (SIG_BLOCK, &caught_signals, &status.sigs) == 0);
return status;
}
/* Leave a critical section. */
static void
cs_leave (struct cs_status status)
{
if (status.valid)
{
/* Ignore failure when restoring the signal mask. */
sigprocmask (SIG_SETMASK, &status.sigs, NULL);
}
}
/* The list of temporary files. */
struct tempnode
{
struct tempnode *volatile next;
pid_t pid; /* If compressed, the pid of compressor, else zero */
char name[1]; /* Actual size is 1 + file name length. */
};
static struct tempnode *volatile temphead;
static struct tempnode *volatile *temptail = &temphead;
struct sortfile
{
char const *name;
pid_t pid; /* If compressed, the pid of compressor, else zero */
};
/* A table where we store compression process states. We clean up all
processes in a timely manner so as not to exhaust system resources,
so we store the info on whether the process is still running, or has
been reaped here. */
static Hash_table *proctab;
enum { INIT_PROCTAB_SIZE = 47 };
enum procstate { ALIVE, ZOMBIE };
/* A proctab entry. The COUNT field is there in case we fork a new
compression process that has the same PID as an old zombie process
that is still in the table (because the process to decompress the
temp file it was associated with hasn't started yet). */
struct procnode
{
pid_t pid;
enum procstate state;
size_t count;
};
static size_t
proctab_hasher (const void *entry, size_t tabsize)
{
const struct procnode *node = entry;
return node->pid % tabsize;
}
static bool
proctab_comparator (const void *e1, const void *e2)
{
const struct procnode *n1 = e1, *n2 = e2;
return n1->pid == n2->pid;
}
/* The total number of forked processes (compressors and decompressors)
that have not been reaped yet. */
static size_t nprocs;
/* The number of child processes we'll allow before we try to reap some. */
enum { MAX_PROCS_BEFORE_REAP = 2 };
/* If 0 < PID, wait for the child process with that PID to exit.
If PID is -1, clean up a random child process which has finished and
return the process ID of that child. If PID is -1 and no processes
have quit yet, return 0 without waiting. */
static pid_t
reap (pid_t pid)
{
int status;
pid_t cpid = waitpid (pid, &status, pid < 0 ? WNOHANG : 0);
if (cpid < 0)
error (SORT_FAILURE, errno, _("waiting for %s [-d]"),
compress_program);
else if (0 < cpid)
{
if (! WIFEXITED (status) || WEXITSTATUS (status))
error (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"),
compress_program);
--nprocs;
}
return cpid;
}
/* Add the PID of a running compression process to proctab, or update
the entry COUNT and STATE fields if it's already there. This also
creates the table for us the first time it's called. */
static void
register_proc (pid_t pid)
{
struct procnode test, *node;
if (! proctab)
{
proctab = hash_initialize (INIT_PROCTAB_SIZE, NULL,
proctab_hasher,
proctab_comparator,
free);
if (! proctab)
xalloc_die ();
}
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node)
{
node->state = ALIVE;
++node->count;
}
else
{
node = xmalloc (sizeof *node);
node->pid = pid;
node->state = ALIVE;
node->count = 1;
if (hash_insert (proctab, node) == NULL)
xalloc_die ();
}
}
/* This is called when we reap a random process. We don't know
whether we have reaped a compression process or a decompression
process until we look in the table. If there's an ALIVE entry for
it, then we have reaped a compression process, so change the state
to ZOMBIE. Otherwise, it's a decompression processes, so ignore it. */
static void
update_proc (pid_t pid)
{
struct procnode test, *node;
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node)
node->state = ZOMBIE;
}
/* This is for when we need to wait for a compression process to exit.
If it has a ZOMBIE entry in the table then it's already dead and has
been reaped. Note that if there's an ALIVE entry for it, it still may
already have died and been reaped if a second process was created with
the same PID. This is probably exceedingly rare, but to be on the safe
side we will have to wait for any compression process with this PID. */
static void
wait_proc (pid_t pid)
{
struct procnode test, *node;
test.pid = pid;
node = hash_lookup (proctab, &test);
if (node->state == ALIVE)
reap (pid);
node->state = ZOMBIE;
if (! --node->count)
{
hash_delete (proctab, node);
free (node);
}
}
/* Keep reaping finished children as long as there are more to reap.
This doesn't block waiting for any of them, it only reaps those
that are already dead. */
static void
reap_some (void)
{
pid_t pid;
while (0 < nprocs && (pid = reap (-1)))
update_proc (pid);
}
/* Clean up any remaining temporary files. */
static void
cleanup (void)
{
struct tempnode const *node;
for (node = temphead; node; node = node->next)
unlink (node->name);
temphead = NULL;
}
/* Cleanup actions to take when exiting. */
static void
exit_cleanup (void)
{
if (temphead)
{
/* Clean up any remaining temporary files in a critical section so
that a signal handler does not try to clean them too. */
struct cs_status cs = cs_enter ();
cleanup ();
cs_leave (cs);
}
close_stdout ();
}
/* Create a new temporary file, returning its newly allocated tempnode.
Store into *PFD the file descriptor open for writing.
If the creation fails, return NULL and store -1 into *PFD if the
failure is due to file descriptor exhaustion and
SURVIVE_FD_EXHAUSTION; otherwise, die. */
static struct tempnode *
create_temp_file (int *pfd, bool survive_fd_exhaustion)
{
static char const slashbase[] = "/sortXXXXXX";
static size_t temp_dir_index;
int fd;
int saved_errno;
char const *temp_dir = temp_dirs[temp_dir_index];
size_t len = strlen (temp_dir);
struct tempnode *node =
xmalloc (offsetof (struct tempnode, name) + len + sizeof slashbase);
char *file = node->name;
struct cs_status cs;
memcpy (file, temp_dir, len);
memcpy (file + len, slashbase, sizeof slashbase);
node->next = NULL;
node->pid = 0;
if (++temp_dir_index == temp_dir_count)
temp_dir_index = 0;
/* Create the temporary file in a critical section, to avoid races. */
cs = cs_enter ();
fd = mkstemp (file);
if (0 <= fd)
{
*temptail = node;
temptail = &node->next;
}
saved_errno = errno;
cs_leave (cs);
errno = saved_errno;
if (fd < 0)
{
if (! (survive_fd_exhaustion && errno == EMFILE))
error (SORT_FAILURE, errno, _("cannot create temporary file in %s"),
quote (temp_dir));
free (node);
node = NULL;
}
*pfd = fd;
return node;
}
/* Predeclare an access pattern for input files.
Ignore any errors -- this is only advisory.
There are a few hints we could possibly provide,
and after careful testing it was decided that
specifying POSIX_FADV_SEQUENTIAL was not detrimental
to any cases. On Linux 2.6.31, this option doubles
the size of read ahead performed and thus was seen to
benefit these cases:
Merging
Sorting with a smaller internal buffer
Reading from faster flash devices
In _addition_ one could also specify other hints...
POSIX_FADV_WILLNEED was tested, but Linux 2.6.31
at least uses that to _synchronously_ prepopulate the cache
with the specified range. While sort does need to
read all of its input before outputting, a synchronous
read of the whole file up front precludes any processing
that sort could do in parallel with the system doing
read ahead of the data. This was seen to have negative effects
in a couple of cases:
Merging
Sorting with a smaller internal buffer
Note this option was seen to shorten the runtime for sort
on a multicore system with lots of RAM and other processes
competing for CPU. It could be argued that more explicit
scheduling hints with `nice` et. al. are more appropriate
for this situation.
POSIX_FADV_NOREUSE is a possibility as it could lower
the priority of input data in the cache as sort will
only need to process it once. However its functionality
has changed over Linux kernel versions and as of 2.6.31
it does nothing and thus we can't depend on what it might
do in future.
POSIX_FADV_DONTNEED is not appropriate for user specified
input files, but for temp files we do want to drop the
cache immediately after processing. This is done implicitly
however when the files are unlinked. */
static void
fadvise_input (FILE *fp)
{
#if HAVE_POSIX_FADVISE
if (fp)
{
int fd = fileno (fp);
ignore_value (posix_fadvise (fd, 0, 0, POSIX_FADV_SEQUENTIAL));
}
#endif
}
/* Return a stream for FILE, opened with mode HOW. A null FILE means
standard output; HOW should be "w". When opening for input, "-"
means standard input. To avoid confusion, do not return file
descriptors STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO when
opening an ordinary FILE. Return NULL if unsuccessful. */
static FILE *
stream_open (const char *file, const char *how)
{
if (!file)
return stdout;
if (*how == 'r')
{
FILE *fp;
if (STREQ (file, "-"))
{
have_read_stdin = true;
fp = stdin;
}
else
fp = fopen (file, how);
fadvise_input (fp);
return fp;
}
return fopen (file, how);
}
/* Same as stream_open, except always return a non-null value; die on
failure. */
static FILE *
xfopen (const char *file, const char *how)
{
FILE *fp = stream_open (file, how);
if (!fp)
die (_("open failed"), file);
return fp;
}
/* Close FP, whose name is FILE, and report any errors. */
static void
xfclose (FILE *fp, char const *file)
{
switch (fileno (fp))
{
case STDIN_FILENO:
/* Allow reading stdin from tty more than once. */
if (feof (fp))
clearerr (fp);
break;
case STDOUT_FILENO:
/* Don't close stdout just yet. close_stdout does that. */
if (fflush (fp) != 0)
die (_("fflush failed"), file);
break;
default:
if (fclose (fp) != 0)
die (_("close failed"), file);
break;
}
}
static void
dup2_or_die (int oldfd, int newfd)
{
if (dup2 (oldfd, newfd) < 0)
error (SORT_FAILURE, errno, _("dup2 failed"));
}
/* Fork a child process for piping to and do common cleanup. The
TRIES parameter tells us how many times to try to fork before
giving up. Return the PID of the child, or -1 (setting errno)
on failure. */
static pid_t
pipe_fork (int pipefds[2], size_t tries)
{
#if HAVE_WORKING_FORK
struct tempnode *saved_temphead;
int saved_errno;
double wait_retry = 0.25;
pid_t pid IF_LINT ( = -1);
struct cs_status cs;
if (pipe (pipefds) < 0)
return -1;
while (tries--)
{
/* This is so the child process won't delete our temp files
if it receives a signal before exec-ing. */
cs = cs_enter ();
saved_temphead = temphead;
temphead = NULL;
pid = fork ();
saved_errno = errno;
if (pid)
temphead = saved_temphead;
cs_leave (cs);
errno = saved_errno;
if (0 <= pid || errno != EAGAIN)
break;
else
{
xnanosleep (wait_retry);
wait_retry *= 2;
reap_some ();
}
}
if (pid < 0)
{
saved_errno = errno;
close (pipefds[0]);
close (pipefds[1]);
errno = saved_errno;
}
else if (pid == 0)
{
close (STDIN_FILENO);
close (STDOUT_FILENO);
}
else
++nprocs;
return pid;
#else /* ! HAVE_WORKING_FORK */
return -1;
#endif
}
/* Create a temporary file and start a compression program to filter output
to that file. Set *PFP to the file handle and if PPID is non-NULL,
set *PPID to the PID of the newly-created process. If the creation
fails, return NULL if the failure is due to file descriptor
exhaustion and SURVIVE_FD_EXHAUSTION; otherwise, die. */
static char *
maybe_create_temp (FILE **pfp, pid_t *ppid, bool survive_fd_exhaustion)
{
int tempfd;
struct tempnode *node = create_temp_file (&tempfd, survive_fd_exhaustion);
char *name;
if (! node)
return NULL;
name = node->name;
if (compress_program)
{
int pipefds[2];
node->pid = pipe_fork (pipefds, MAX_FORK_TRIES_COMPRESS);
if (0 < node->pid)
{
close (tempfd);
close (pipefds[0]);
tempfd = pipefds[1];
register_proc (node->pid);
}
else if (node->pid == 0)
{
close (pipefds[1]);
dup2_or_die (tempfd, STDOUT_FILENO);
close (tempfd);
dup2_or_die (pipefds[0], STDIN_FILENO);
close (pipefds[0]);
if (execlp (compress_program, compress_program, (char *) NULL) < 0)
error (SORT_FAILURE, errno, _("couldn't execute %s"),
compress_program);
}
else
node->pid = 0;
}
*pfp = fdopen (tempfd, "w");
if (! *pfp)
die (_("couldn't create temporary file"), name);
if (ppid)
*ppid = node->pid;
return name;
}
/* Create a temporary file and start a compression program to filter output
to that file. Set *PFP to the file handle and if *PPID is non-NULL,
set it to the PID of the newly-created process. Die on failure. */
static char *
create_temp (FILE **pfp, pid_t *ppid)
{
return maybe_create_temp (pfp, ppid, false);
}
/* Open a compressed temp file and start a decompression process through
which to filter the input. PID must be the valid processes ID of the
process used to compress the file. Return NULL (setting errno to
EMFILE) if we ran out of file descriptors, and die on any other
kind of failure. */
static FILE *
open_temp (const char *name, pid_t pid)
{
int tempfd, pipefds[2];
FILE *fp = NULL;
wait_proc (pid);
tempfd = open (name, O_RDONLY);
if (tempfd < 0)
return NULL;
switch (pipe_fork (pipefds, MAX_FORK_TRIES_DECOMPRESS))
{
case -1:
if (errno != EMFILE)
error (SORT_FAILURE, errno, _("couldn't create process for %s -d"),
compress_program);
close (tempfd);
errno = EMFILE;
break;
case 0:
close (pipefds[0]);
dup2_or_die (tempfd, STDIN_FILENO);
close (tempfd);
dup2_or_die (pipefds[1], STDOUT_FILENO);
close (pipefds[1]);
execlp (compress_program, compress_program, "-d", (char *) NULL);
error (SORT_FAILURE, errno, _("couldn't execute %s -d"),
compress_program);
default:
close (tempfd);
close (pipefds[1]);
fp = fdopen (pipefds[0], "r");
if (! fp)
{
int saved_errno = errno;
close (pipefds[0]);
errno = saved_errno;
}
break;
}
return fp;
}
/* Append DIR to the array of temporary directory names. */
static void
add_temp_dir (char const *dir)
{
if (temp_dir_count == temp_dir_alloc)
temp_dirs = X2NREALLOC (temp_dirs, &temp_dir_alloc);
temp_dirs[temp_dir_count++] = dir;
}
/* Remove NAME from the list of temporary files. */
static void
zaptemp (const char *name)
{
struct tempnode *volatile *pnode;
struct tempnode *node;
struct tempnode *next;
int unlink_status;
int unlink_errno = 0;
struct cs_status cs;
for (pnode = &temphead; (node = *pnode)->name != name; pnode = &node->next)
continue;
/* Unlink the temporary file in a critical section to avoid races. */
next = node->next;
cs = cs_enter ();
unlink_status = unlink (name);
unlink_errno = errno;
*pnode = next;
cs_leave (cs);
if (unlink_status != 0)
error (0, unlink_errno, _("warning: cannot remove: %s"), name);
if (! next)
temptail = pnode;
free (node);
}
#if HAVE_NL_LANGINFO
static int
struct_month_cmp (const void *m1, const void *m2)
{
struct month const *month1 = m1;
struct month const *month2 = m2;
return strcmp (month1->name, month2->name);
}
#endif
/* Initialize the character class tables. */
static void
inittables (void)
{
size_t i;
for (i = 0; i < UCHAR_LIM; ++i)
{
blanks[i] = !! isblank (i);
nonprinting[i] = ! isprint (i);
nondictionary[i] = ! isalnum (i) && ! isblank (i);
fold_toupper[i] = toupper (i);
}
#if HAVE_NL_LANGINFO
/* If we're not in the "C" locale, read different names for months. */
if (hard_LC_TIME)
{
for (i = 0; i < MONTHS_PER_YEAR; i++)
{
char const *s;
size_t s_len;
size_t j, k;
char *name;
s = (char *) nl_langinfo (ABMON_1 + i);
s_len = strlen (s);
monthtab[i].name = name = xmalloc (s_len + 1);
monthtab[i].val = i + 1;
for (j = k = 0; j < s_len; j++)
if (! isblank (to_uchar (s[j])))
name[k++] = fold_toupper[to_uchar (s[j])];
name[k] = '\0';
}
qsort ((void *) monthtab, MONTHS_PER_YEAR,
sizeof *monthtab, struct_month_cmp);
}
#endif
}
/* Specify how many inputs may be merged at once.
This may be set on the command-line with the
--batch-size option. */
static void
specify_nmerge (int oi, char c, char const *s)
{
uintmax_t n;
struct rlimit rlimit;
enum strtol_error e = xstrtoumax (s, NULL, 10, &n, NULL);
/* Try to find out how many file descriptors we'll be able
to open. We need at least nmerge + 3 (STDIN_FILENO,
STDOUT_FILENO and STDERR_FILENO). */
unsigned int max_nmerge = ((getrlimit (RLIMIT_NOFILE, &rlimit) == 0
? rlimit.rlim_cur
: OPEN_MAX)
- 3);
if (e == LONGINT_OK)
{
nmerge = n;
if (nmerge != n)
e = LONGINT_OVERFLOW;
else
{
if (nmerge < 2)
{
error (0, 0, _("invalid --%s argument %s"),
long_options[oi].name, quote (s));
error (SORT_FAILURE, 0,
_("minimum --%s argument is %s"),
long_options[oi].name, quote ("2"));
}
else if (max_nmerge < nmerge)
{
e = LONGINT_OVERFLOW;
}
else
return;
}
}
if (e == LONGINT_OVERFLOW)
{
char max_nmerge_buf[INT_BUFSIZE_BOUND (max_nmerge)];
error (0, 0, _("--%s argument %s too large"),
long_options[oi].name, quote (s));
error (SORT_FAILURE, 0,
_("maximum --%s argument with current rlimit is %s"),
long_options[oi].name,
uinttostr (max_nmerge, max_nmerge_buf));
}
else
xstrtol_fatal (e, oi, c, long_options, s);
}
/* Specify the amount of main memory to use when sorting. */
static void
specify_sort_size (int oi, char c, char const *s)
{
uintmax_t n;
char *suffix;
enum strtol_error e = xstrtoumax (s, &suffix, 10, &n, "EgGkKmMPtTYZ");
/* The default unit is KiB. */
if (e == LONGINT_OK && ISDIGIT (suffix[-1]))
{
if (n <= UINTMAX_MAX / 1024)
n *= 1024;
else
e = LONGINT_OVERFLOW;
}
/* A 'b' suffix means bytes; a '%' suffix means percent of memory. */
if (e == LONGINT_INVALID_SUFFIX_CHAR && ISDIGIT (suffix[-1]) && ! suffix[1])
switch (suffix[0])
{
case 'b':
e = LONGINT_OK;
break;
case '%':
{
double mem = physmem_total () * n / 100;
/* Use "<", not "<=", to avoid problems with rounding. */
if (mem < UINTMAX_MAX)
{
n = mem;
e = LONGINT_OK;
}
else
e = LONGINT_OVERFLOW;
}
break;
}
if (e == LONGINT_OK)
{
/* If multiple sort sizes are specified, take the maximum, so
that option order does not matter. */
if (n < sort_size)
return;
sort_size = n;
if (sort_size == n)
{
sort_size = MAX (sort_size, MIN_SORT_SIZE);
return;
}
e = LONGINT_OVERFLOW;
}
xstrtol_fatal (e, oi, c, long_options, s);
}
/* Specify the number of threads to spawn during internal sort. */
static unsigned long int
specify_nthreads (int oi, char c, char const *s)
{
unsigned long int nthreads;
enum strtol_error e = xstrtoul (s, NULL, 10, &nthreads, "");
if (e == LONGINT_OVERFLOW)
return ULONG_MAX;
if (e != LONGINT_OK)
xstrtol_fatal (e, oi, c, long_options, s);
if (nthreads == 0)
error (SORT_FAILURE, 0, _("number in parallel must be nonzero"));
return nthreads;
}
/* Return the default sort size. */
static size_t
default_sort_size (void)
{
/* Let MEM be available memory or 1/8 of total memory, whichever
is greater. */
double avail = physmem_available ();
double total = physmem_total ();
double mem = MAX (avail, total / 8);
struct rlimit rlimit;
/* Let SIZE be MEM, but no more than the maximum object size or
system resource limits. Avoid the MIN macro here, as it is not
quite right when only one argument is floating point. Don't
bother to check for values like RLIM_INFINITY since in practice
they are not much less than SIZE_MAX. */
size_t size = SIZE_MAX;
if (mem < size)
size = mem;
if (getrlimit (RLIMIT_DATA, &rlimit) == 0 && rlimit.rlim_cur < size)
size = rlimit.rlim_cur;
#ifdef RLIMIT_AS
if (getrlimit (RLIMIT_AS, &rlimit) == 0 && rlimit.rlim_cur < size)
size = rlimit.rlim_cur;
#endif
/* Leave a large safety margin for the above limits, as failure can
occur when they are exceeded. */
size /= 2;
#ifdef RLIMIT_RSS
/* Leave a 1/16 margin for RSS to leave room for code, stack, etc.
Exceeding RSS is not fatal, but can be quite slow. */
if (getrlimit (RLIMIT_RSS, &rlimit) == 0 && rlimit.rlim_cur / 16 * 15 < size)
size = rlimit.rlim_cur / 16 * 15;
#endif
/* Use no less than the minimum. */
return MAX (size, MIN_SORT_SIZE);
}
/* Return the sort buffer size to use with the input files identified
by FPS and FILES, which are alternate names of the same files.
NFILES gives the number of input files; NFPS may be less. Assume
that each input line requires LINE_BYTES extra bytes' worth of line
information. Do not exceed the size bound specified by the user
(or a default size bound, if the user does not specify one). */
static size_t
sort_buffer_size (FILE *const *fps, size_t nfps,
char *const *files, size_t nfiles,
size_t line_bytes)
{
/* A bound on the input size. If zero, the bound hasn't been
determined yet. */
static size_t size_bound;
/* In the worst case, each input byte is a newline. */
size_t worst_case_per_input_byte = line_bytes + 1;
/* Keep enough room for one extra input line and an extra byte.
This extra room might be needed when preparing to read EOF. */
size_t size = worst_case_per_input_byte + 1;
size_t i;
for (i = 0; i < nfiles; i++)
{
struct stat st;
off_t file_size;
size_t worst_case;
if ((i < nfps ? fstat (fileno (fps[i]), &st)
: STREQ (files[i], "-") ? fstat (STDIN_FILENO, &st)
: stat (files[i], &st))
!= 0)
die (_("stat failed"), files[i]);
if (S_ISREG (st.st_mode))
file_size = st.st_size;
else
{
/* The file has unknown size. If the user specified a sort
buffer size, use that; otherwise, guess the size. */
if (sort_size)
return sort_size;
file_size = INPUT_FILE_SIZE_GUESS;
}
if (! size_bound)
{
size_bound = sort_size;
if (! size_bound)
size_bound = default_sort_size ();
}
/* Add the amount of memory needed to represent the worst case
where the input consists entirely of newlines followed by a
single non-newline. Check for overflow. */
worst_case = file_size * worst_case_per_input_byte + 1;
if (file_size != worst_case / worst_case_per_input_byte
|| size_bound - size <= worst_case)
return size_bound;
size += worst_case;
}
return size;
}
/* Initialize BUF. Reserve LINE_BYTES bytes for each line; LINE_BYTES
must be at least sizeof (struct line). Allocate ALLOC bytes
initially. */
static void
initbuf (struct buffer *buf, size_t line_bytes, size_t alloc)
{
/* Ensure that the line array is properly aligned. If the desired
size cannot be allocated, repeatedly halve it until allocation
succeeds. The smaller allocation may hurt overall performance,
but that's better than failing. */
while (true)
{
alloc += sizeof (struct line) - alloc % sizeof (struct line);
buf->buf = malloc (alloc);
if (buf->buf)
break;
alloc /= 2;
if (alloc <= line_bytes + 1)
xalloc_die ();
}
buf->line_bytes = line_bytes;
buf->alloc = alloc;
buf->used = buf->left = buf->nlines = 0;
buf->eof = false;
}
/* Return one past the limit of the line array. */
static inline struct line *
buffer_linelim (struct buffer const *buf)
{
return (struct line *) (buf->buf + buf->alloc);
}
/* Return a pointer to the first character of the field specified
by KEY in LINE. */
static char *
begfield (const struct line *line, const struct keyfield *key)
{
char *ptr = line->text, *lim = ptr + line->length - 1;
size_t sword = key->sword;
size_t schar = key->schar;
/* The leading field separator itself is included in a field when -t
is absent. */
if (tab != TAB_DEFAULT)
while (ptr < lim && sword--)
{
while (ptr < lim && *ptr != tab)
++ptr;
if (ptr < lim)
++ptr;
}
else
while (ptr < lim && sword--)
{
while (ptr < lim && blanks[to_uchar (*ptr)])
++ptr;
while (ptr < lim && !blanks[to_uchar (*ptr)])
++ptr;
}
/* If we're ignoring leading blanks when computing the Start
of the field, skip past them here. */
if (key->skipsblanks)
while (ptr < lim && blanks[to_uchar (*ptr)])
++ptr;
/* Advance PTR by SCHAR (if possible), but no further than LIM. */
ptr = MIN (lim, ptr + schar);
return ptr;
}
/* Return the limit of (a pointer to the first character after) the field
in LINE specified by KEY. */
static char *
limfield (const struct line *line, const struct keyfield *key)
{
char *ptr = line->text, *lim = ptr + line->length - 1;
size_t eword = key->eword, echar = key->echar;
if (echar == 0)
eword++; /* Skip all of end field. */
/* Move PTR past EWORD fields or to one past the last byte on LINE,
whichever comes first. If there are more than EWORD fields, leave
PTR pointing at the beginning of the field having zero-based index,
EWORD. If a delimiter character was specified (via -t), then that
`beginning' is the first character following the delimiting TAB.
Otherwise, leave PTR pointing at the first `blank' character after
the preceding field. */
if (tab != TAB_DEFAULT)
while (ptr < lim && eword--)
{
while (ptr < lim && *ptr != tab)
++ptr;
if (ptr < lim && (eword || echar))
++ptr;
}
else
while (ptr < lim && eword--)
{
while (ptr < lim && blanks[to_uchar (*ptr)])
++ptr;
while (ptr < lim && !blanks[to_uchar (*ptr)])
++ptr;
}
#ifdef POSIX_UNSPECIFIED
/* The following block of code makes GNU sort incompatible with
standard Unix sort, so it's ifdef'd out for now.
The POSIX spec isn't clear on how to interpret this.
FIXME: request clarification.
From: kwzh@gnu.ai.mit.edu (Karl Heuer)
Date: Thu, 30 May 96 12:20:41 -0400
[Translated to POSIX 1003.1-2001 terminology by Paul Eggert.]
[...]I believe I've found another bug in `sort'.
$ cat /tmp/sort.in
a b c 2 d
pq rs 1 t
$ textutils-1.15/src/sort -k1.7,1.7 </tmp/sort.in
a b c 2 d
pq rs 1 t
$ /bin/sort -k1.7,1.7 </tmp/sort.in
pq rs 1 t
a b c 2 d
Unix sort produced the answer I expected: sort on the single character
in column 7. GNU sort produced different results, because it disagrees
on the interpretation of the key-end spec "M.N". Unix sort reads this
as "skip M-1 fields, then N-1 characters"; but GNU sort wants it to mean
"skip M-1 fields, then either N-1 characters or the rest of the current
field, whichever comes first". This extra clause applies only to
key-ends, not key-starts.
*/
/* Make LIM point to the end of (one byte past) the current field. */
if (tab != TAB_DEFAULT)
{
char *newlim;
newlim = memchr (ptr, tab, lim - ptr);
if (newlim)
lim = newlim;
}
else
{
char *newlim;
newlim = ptr;
while (newlim < lim && blanks[to_uchar (*newlim)])
++newlim;
while (newlim < lim && !blanks[to_uchar (*newlim)])
++newlim;
lim = newlim;
}
#endif
if (echar != 0) /* We need to skip over a portion of the end field. */
{
/* If we're ignoring leading blanks when computing the End
of the field, skip past them here. */
if (key->skipeblanks)
while (ptr < lim && blanks[to_uchar (*ptr)])
++ptr;
/* Advance PTR by ECHAR (if possible), but no further than LIM. */
ptr = MIN (lim, ptr + echar);
}
return ptr;
}
/* Fill BUF reading from FP, moving buf->left bytes from the end
of buf->buf to the beginning first. If EOF is reached and the
file wasn't terminated by a newline, supply one. Set up BUF's line
table too. FILE is the name of the file corresponding to FP.
Return true if some input was read. */
static bool
fillbuf (struct buffer *buf, FILE *fp, char const *file)
{
struct keyfield const *key = keylist;
char eol = eolchar;
size_t line_bytes = buf->line_bytes;
size_t mergesize = merge_buffer_size - MIN_MERGE_BUFFER_SIZE;
if (buf->eof)
return false;
if (buf->used != buf->left)
{
memmove (buf->buf, buf->buf + buf->used - buf->left, buf->left);
buf->used = buf->left;
buf->nlines = 0;
}
while (true)
{
char *ptr = buf->buf + buf->used;
struct line *linelim = buffer_linelim (buf);
struct line *line = linelim - buf->nlines;
size_t avail = (char *) linelim - buf->nlines * line_bytes - ptr;
char *line_start = buf->nlines ? line->text + line->length : buf->buf;
while (line_bytes + 1 < avail)
{
/* Read as many bytes as possible, but do not read so many
bytes that there might not be enough room for the
corresponding line array. The worst case is when the
rest of the input file consists entirely of newlines,
except that the last byte is not a newline. */
size_t readsize = (avail - 1) / (line_bytes + 1);
size_t bytes_read = fread (ptr, 1, readsize, fp);
char *ptrlim = ptr + bytes_read;
char *p;
avail -= bytes_read;
if (bytes_read != readsize)
{
if (ferror (fp))
die (_("read failed"), file);
if (feof (fp))
{
buf->eof = true;
if (buf->buf == ptrlim)
return false;
if (ptrlim[-1] != eol)
*ptrlim++ = eol;
}
}
/* Find and record each line in the just-read input. */
while ((p = memchr (ptr, eol, ptrlim - ptr)))
{
/* Delimit the line with NUL. This eliminates the need to
temporarily replace the last byte with NUL when calling
xmemcoll(), which increases performance. */
*p = '\0';
ptr = p + 1;
line--;
line->text = line_start;
line->length = ptr - line_start;
mergesize = MAX (mergesize, line->length);
avail -= line_bytes;
if (key)
{
/* Precompute the position of the first key for
efficiency. */
line->keylim = (key->eword == SIZE_MAX
? p
: limfield (line, key));
if (key->sword != SIZE_MAX)
line->keybeg = begfield (line, key);
else
{
if (key->skipsblanks)
while (blanks[to_uchar (*line_start)])
line_start++;
line->keybeg = line_start;
}
}
line_start = ptr;
}
ptr = ptrlim;
if (buf->eof)
break;
}
buf->used = ptr - buf->buf;
buf->nlines = buffer_linelim (buf) - line;
if (buf->nlines != 0)
{
buf->left = ptr - line_start;
merge_buffer_size = mergesize + MIN_MERGE_BUFFER_SIZE;
return true;
}
{
/* The current input line is too long to fit in the buffer.
Double the buffer size and try again, keeping it properly
aligned. */
size_t line_alloc = buf->alloc / sizeof (struct line);
buf->buf = x2nrealloc (buf->buf, &line_alloc, sizeof (struct line));
buf->alloc = line_alloc * sizeof (struct line);
}
}
}
/* Exit with an error if a mixture of SI and IEC units detected. */
static bool
check_mixed_SI_IEC (char prefix, struct keyfield *key)
{
int iec_present = prefix == 'i';
if (key)
{
if (key->iec_present != -1 && iec_present != key->iec_present)
error (SORT_FAILURE, 0, _("both SI and IEC prefixes present on units"));
key->iec_present = iec_present;
}
return iec_present;
}
/* Return an integer which represents the order of magnitude of
the unit following the number. NUMBER can contain thousands separators
or a decimal point, but not have preceeding blanks.
Negative numbers return a negative unit order. */
static int
find_unit_order (const char *number, struct keyfield *key, char const **endptr)
{
static const char orders [UCHAR_LIM] =
{
#if SOME_DAY_WE_WILL_REQUIRE_C99
['K']=1, ['M']=2, ['G']=3, ['T']=4, ['P']=5, ['E']=6, ['Z']=7, ['Y']=8,
['k']=1,
#else
/* Generate the following table with this command:
perl -e 'my %a=(k=>1, K=>1, M=>2, G=>3, T=>4, P=>5, E=>6, Z=>7, Y=>8);
foreach my $i (0..255) {my $c=chr($i); $a{$c} ||= 0;print "$a{$c}, "}'\
|fmt */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 3,
0, 0, 0, 1, 0, 2, 0, 0, 5, 0, 0, 0, 4, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
#endif
};
const unsigned char *p = number;
int sign = 1;
if (*p == '-')
{
sign = -1;
p++;
}
/* Scan to end of number.
Decimals or separators not followed by digits stop the scan.
Numbers ending in decimals or separators are thus considered
to be lacking in units.
FIXME: add support for multibyte thousands_sep and decimal_point. */
while (ISDIGIT (*p))
{
p++;
if (*p == decimal_point && ISDIGIT (*(p + 1)))
p += 2;
else if (*p == thousands_sep && ISDIGIT (*(p + 1)))
p += 2;
}
int order = orders[*p];
/* For valid units check for MiB vs MB etc. */
if (order)
{
p++;
p += check_mixed_SI_IEC (*p, key);
}
if (endptr)
*endptr = p;
return sign * order;
}
/* Compare numbers ending in units with SI xor IEC prefixes
<none/unknown> < K/k < M < G < T < P < E < Z < Y
Assume that numbers are properly abbreviated.
i.e. input will never have both 6000K and 5M. */
static int
human_numcompare (const char *a, const char *b, struct keyfield *key,
char const **ea)
{
while (blanks[to_uchar (*a)])
a++;
while (blanks[to_uchar (*b)])
b++;
int order_a = find_unit_order (a, key, ea);
int order_b = find_unit_order (b, key, NULL);
return (order_a > order_b ? 1
: order_a < order_b ? -1
: strnumcmp (a, b, decimal_point, thousands_sep));
}
/* Compare strings A and B as numbers without explicitly converting them to
machine numbers. Comparatively slow for short strings, but asymptotically
hideously fast. */
static int
numcompare (const char *a, const char *b, char const **ea)
{
while (blanks[to_uchar (*a)])
a++;
while (blanks[to_uchar (*b)])
b++;
if (debug)
{
/* Approximate strnumcmp extents with find_unit_order. */
if (find_unit_order (a, NULL, ea))
{
*ea -= 1; /* ignore the order letter */
*ea -= (**ea == 'i'); /* and IEC prefix */
}
}
return strnumcmp (a, b, decimal_point, thousands_sep);
}
static int
general_numcompare (const char *sa, const char *sb, char const **ea)
{
/* FIXME: maybe add option to try expensive FP conversion
only if A and B can't be compared more cheaply/accurately. */
#if HAVE_C99_STRTOLD /* provided by c-strtold module. */
# define long_double long double
#else
# define long_double double
# undef strtold
# define strtold strtod
#endif
char *eb;
long_double a = strtold (sa, (char **) ea);
long_double b = strtold (sb, &eb);
/* Put conversion errors at the start of the collating sequence. */
if (sa == *ea)
return sb == eb ? 0 : -1;
if (sb == eb)
return 1;
/* Sort numbers in the usual way, where -0 == +0. Put NaNs after
conversion errors but before numbers; sort them by internal
bit-pattern, for lack of a more portable alternative. */
return (a < b ? -1
: a > b ? 1
: a == b ? 0
: b == b ? -1
: a == a ? 1
: memcmp ((char *) &a, (char *) &b, sizeof a));
}
/* Return an integer in 1..12 of the month name MONTH with length LEN.
Return 0 if the name in S is not recognized. */
static int
getmonth (char const *month, size_t len, char const **ea)
{
size_t lo = 0;
size_t hi = MONTHS_PER_YEAR;
char const *monthlim = month + len;
while (true)
{
if (month == monthlim)
return 0;
if (!blanks[to_uchar (*month)])
break;
++month;
}
do
{
size_t ix = (lo + hi) / 2;
char const *m = month;
char const *n = monthtab[ix].name;
for (;; m++, n++)
{
if (!*n)
{
if (ea)
*ea = m;
return monthtab[ix].val;
}
if (m == monthlim || fold_toupper[to_uchar (*m)] < to_uchar (*n))
{
hi = ix;
break;
}
else if (fold_toupper[to_uchar (*m)] > to_uchar (*n))
{
lo = ix + 1;
break;
}
}
}
while (lo < hi);
return 0;
}
/* A source of random data. */
static struct randread_source *randread_source;
/* Return the Ith randomly-generated state. The caller must invoke
random_state (H) for all H less than I before invoking random_state
(I). */
static struct md5_ctx
random_state (size_t i)
{
/* An array of states resulting from the random data, and counts of
its used and allocated members. */
static struct md5_ctx *state;
static size_t used;
static size_t allocated;
struct md5_ctx *s = &state[i];
if (used <= i)
{
unsigned char buf[MD5_DIGEST_SIZE];
used++;
if (allocated <= i)
{
state = X2NREALLOC (state, &allocated);
s = &state[i];
}
randread (randread_source, buf, sizeof buf);
md5_init_ctx (s);
md5_process_bytes (buf, sizeof buf, s);
}
return *s;
}
/* Compare the hashes of TEXTA with length LENGTHA to those of TEXTB
with length LENGTHB. Return negative if less, zero if equal,
positive if greater. */
static int
cmp_hashes (char const *texta, size_t lena,
char const *textb, size_t lenb)
{
/* Try random hashes until a pair of hashes disagree. But if the
first pair of random hashes agree, check whether the keys are
identical and if so report no difference. */
int diff;
size_t i;
for (i = 0; ; i++)
{
uint32_t dig[2][MD5_DIGEST_SIZE / sizeof (uint32_t)];
struct md5_ctx s[2];
s[0] = s[1] = random_state (i);
md5_process_bytes (texta, lena, &s[0]); md5_finish_ctx (&s[0], dig[0]);
md5_process_bytes (textb, lenb, &s[1]); md5_finish_ctx (&s[1], dig[1]);
diff = memcmp (dig[0], dig[1], sizeof dig[0]);
if (diff != 0)
break;
if (i == 0 && lena == lenb && memcmp (texta, textb, lena) == 0)
break;
}
return diff;
}
/* Compare the keys TEXTA (of length LENA) and TEXTB (of length LENB)
using one or more random hash functions. */
static int
compare_random (char *restrict texta, size_t lena,
char *restrict textb, size_t lenb)
{
int diff;
if (! hard_LC_COLLATE)
diff = cmp_hashes (texta, lena, textb, lenb);
else
{
/* Transform the text into the basis of comparison, so that byte
strings that would otherwise considered to be equal are
considered equal here even if their bytes differ. */
char *buf = NULL;
char stackbuf[4000];
size_t tlena = xmemxfrm (stackbuf, sizeof stackbuf, texta, lena);
bool a_fits = tlena <= sizeof stackbuf;
size_t tlenb = xmemxfrm ((a_fits ? stackbuf + tlena : NULL),
(a_fits ? sizeof stackbuf - tlena : 0),
textb, lenb);
if (a_fits && tlena + tlenb <= sizeof stackbuf)
buf = stackbuf;
else
{
/* Adding 1 to the buffer size lets xmemxfrm run a bit
faster by avoiding the need for an extra buffer copy. */
buf = xmalloc (tlena + tlenb + 1);
xmemxfrm (buf, tlena + 1, texta, lena);
xmemxfrm (buf + tlena, tlenb + 1, textb, lenb);
}
diff = cmp_hashes (buf, tlena, buf + tlena, tlenb);
if (buf != stackbuf)
free (buf);
}
return diff;
}
/* Compare the keys TEXTA (of length LENA) and TEXTB (of length LENB)
using filevercmp. See lib/filevercmp.h for function description. */
static int
compare_version (char *restrict texta, size_t lena,
char *restrict textb, size_t lenb)
{
int diff;
/* It is necessary to save the character after the end of the field.
"filevercmp" works with NUL terminated strings. Our blocks of
text are not necessarily terminated with a NUL byte. */
char sv_a = texta[lena];
char sv_b = textb[lenb];
texta[lena] = '\0';
textb[lenb] = '\0';
diff = filevercmp (texta, textb);
texta[lena] = sv_a;
textb[lenb] = sv_b;
return diff;
}
/* For debug mode, count tabs in the passed string
so we can adjust the widths returned by mbswidth.
FIXME: Should we generally be counting non printable chars? */
static size_t
count_tabs (char const *text, const size_t len)
{
size_t tabs = 0;
size_t tlen = strnlen (text, len);
while (tlen--)
{
if (*text++ == '\t')
tabs++;
}
return tabs;
}
/* For debug mode, "underline" a key at the
specified offset and screen width. */
static void
mark_key (size_t offset, size_t width)
{
printf ("%*s", (int) offset, "");
if (!width)
printf (_("^ no match for key\n"));
else
{
while (width--)
putchar ('_');
putchar ('\n');
}
}
/* For debug mode, determine the screen offset and width
to highlight for a key, and then output the highlight. */
static void
debug_key (char const *sline, char const *sfield, char const *efield,
size_t flen, bool skipb)
{
char const *sa = sfield;
if (skipb) /* This key type implicitly skips leading blanks. */
{
while (sa < efield && blanks[to_uchar (*sa)])
{
sa++;
if (flen)
flen--; /* This assumes TABs same width as SPACEs. */
}
}
size_t offset = mbsnwidth (sline, sfield - sline, 0) + (sa - sfield);
offset += count_tabs (sline, sfield - sline);
size_t width = mbsnwidth (sa, flen, 0);
width += count_tabs (sa, flen);
mark_key (offset, width);
}
/* Testing if a key is numeric is done in various places. */
static inline bool
key_numeric (struct keyfield const *key)
{
return key->numeric || key->general_numeric || key->human_numeric;
}
/* Return whether sorting options specified for key. */
static bool
default_key_compare (struct keyfield const *key)
{
return ! (key->ignore
|| key->translate
|| key->skipsblanks
|| key->skipeblanks
|| key_numeric (key)
|| key->month
|| key->version
|| key->random
/* || key->reverse */
);
}
/* Convert a key to the short options used to specify it. */
static void
key_to_opts (struct keyfield const *key, char *opts)
{
if (key->skipsblanks || key->skipeblanks)
*opts++ = 'b';/* either disables global -b */
if (key->ignore == nondictionary)
*opts++ = 'd';
if (key->translate)
*opts++ = 'f';
if (key->general_numeric)
*opts++ = 'g';
if (key->human_numeric)
*opts++ = 'h';
if (key->ignore == nonprinting)
*opts++ = 'i';
if (key->month)
*opts++ = 'M';
if (key->numeric)
*opts++ = 'n';
if (key->random)
*opts++ = 'R';
if (key->reverse)
*opts++ = 'r';
if (key->version)
*opts++ = 'V';
*opts = '\0';
}
/* Output data independent key warnings to stderr. */
static void
key_warnings (struct keyfield const *gkey, bool gkey_only)
{
struct keyfield const *key;
struct keyfield ugkey = *gkey;
unsigned long keynum = 1;
for (key = keylist; key; key = key->next, keynum++)
{
if (key->obsolete_used)
{
size_t sword = key->sword;
size_t eword = key->eword;
char tmp[INT_BUFSIZE_BOUND (sword)];
/* obsolescent syntax +A.x -B.y is equivalent to:
-k A+1.x+1,B.y (when y = 0)
-k A+1.x+1,B+1.y (when y > 0) */
char obuf[INT_BUFSIZE_BOUND (sword) * 2 + 4]; /* +# -# */
char nbuf[INT_BUFSIZE_BOUND (sword) * 2 + 5]; /* -k #,# */
char *po = obuf;
char *pn = nbuf;
if (sword == SIZE_MAX)
sword++;
po = stpcpy (stpcpy (po, "+"), umaxtostr (sword, tmp));
pn = stpcpy (stpcpy (pn, "-k "), umaxtostr (sword + 1, tmp));
if (key->eword != SIZE_MAX)
{
po = stpcpy (stpcpy (po, " -"), umaxtostr (eword + 1, tmp));
pn = stpcpy (stpcpy (pn, ","),
umaxtostr (eword + 1
+ (key->echar == SIZE_MAX), tmp));
}
error (0, 0, _("obsolescent key `%s' used; consider `%s' instead"),
obuf, nbuf);
}
/* Warn about field specs that will never match. */
if (key->sword != SIZE_MAX && key->eword < key->sword)
error (0, 0, _("key %lu has zero width and will be ignored"), keynum);
/* Warn about significant leading blanks. */
bool implicit_skip = key_numeric (key) || key->month;
bool maybe_space_aligned = !hard_LC_COLLATE && default_key_compare (key)
&& !(key->schar || key->echar);
bool line_offset = key->eword == 0 && key->echar != 0; /* -k1.x,1.y */
if (!gkey_only && tab == TAB_DEFAULT && !line_offset
&& ((!key->skipsblanks && !(implicit_skip || maybe_space_aligned))
|| (!key->skipsblanks && key->schar)
|| (!key->skipeblanks && key->echar)))
error (0, 0, _("leading blanks are significant in key %lu; "
"consider also specifying `b'"), keynum);
/* Warn about numeric comparisons spanning fields,
as field delimiters could be interpreted as part
of the number (maybe only in other locales). */
if (!gkey_only && key_numeric (key))
{
size_t sword = key->sword + 1;
size_t eword = key->eword + 1;
if (!sword)
sword++;
if (sword != eword)
error (0, 0, _("key %lu is numeric and spans multiple fields"),
keynum);
}
/* Flag global options not copied or specified in any key. */
if (ugkey.ignore && (ugkey.ignore == key->ignore))
ugkey.ignore = NULL;
if (ugkey.translate && (ugkey.translate == key->translate))
ugkey.translate = NULL;
ugkey.skipsblanks &= !key->skipsblanks;
ugkey.skipeblanks &= !key->skipeblanks;
ugkey.month &= !key->month;
ugkey.numeric &= !key->numeric;
ugkey.general_numeric &= !key->general_numeric;
ugkey.human_numeric &= !key->human_numeric;
ugkey.random &= !key->random;
ugkey.version &= !key->version;
ugkey.reverse &= !key->reverse;
}
/* Warn about ignored global options flagged above.
Note if gkey is the only one in the list, all flags are cleared. */
if (!default_key_compare (&ugkey)
|| (ugkey.reverse && (stable || unique) && keylist))
{
bool ugkey_reverse = ugkey.reverse;
if (!(stable || unique))
ugkey.reverse = false;
/* The following is too big, but guaranteed to be "big enough". */
char opts[sizeof short_options];
key_to_opts (&ugkey, opts);
error (0, 0,
ngettext ("option `-%s' is ignored",
"options `-%s' are ignored",
select_plural (strlen (opts))), opts);
ugkey.reverse = ugkey_reverse;
}
if (ugkey.reverse && !(stable || unique) && keylist)
error (0, 0, _("option `-r' only applies to last-resort comparison"));
}
/* Compare two lines A and B trying every key in sequence until there
are no more keys or a difference is found. */
static int
keycompare (const struct line *a, const struct line *b, bool show_debug)
{
struct keyfield *key = keylist;
/* For the first iteration only, the key positions have been
precomputed for us. */
char *texta = a->keybeg;
char *textb = b->keybeg;
char *lima = a->keylim;
char *limb = b->keylim;
int diff;
while (true)
{
char const *translate = key->translate;
bool const *ignore = key->ignore;
bool skipb = false; /* Whether key type auto skips leading blanks. */
/* Treat field ends before field starts as empty fields. */
lima = MAX (texta, lima);
limb = MAX (textb, limb);
/* Find the lengths. */
size_t lena = lima - texta;
size_t lenb = limb - textb;
/* Actually compare the fields. */
if (key->random)
diff = compare_random (texta, lena, textb, lenb);
else if (key_numeric (key))
{
char savea = *lima, saveb = *limb;
char const* ea = lima;
*lima = *limb = '\0';
diff = (key->numeric ? numcompare (texta, textb, &ea)
: key->general_numeric ? general_numcompare (texta, textb,
&ea)
: human_numcompare (texta, textb, key, &ea));
if (show_debug)
{
lena = ea - texta;
skipb = true;
}
*lima = savea, *limb = saveb;
}
else if (key->version)
diff = compare_version (texta, lena, textb, lenb);
else if (key->month)
{
char const *ea = lima;
int amon = getmonth (texta, lena, &ea);
diff = amon - getmonth (textb, lenb, NULL);
if (show_debug)
{
lena = amon ? ea - texta : 0;
skipb = true;
}
}
/* Sorting like this may become slow, so in a simple locale the user
can select a faster sort that is similar to ascii sort. */
else if (hard_LC_COLLATE)
{
/* FIXME: for debug, account for skipped chars, while handling mb chars.
Generally perhaps xmemfrm could be used to determine chars that are
excluded from the collating order? */
if (ignore || translate)
{
char buf[4000];
size_t size = lena + 1 + lenb + 1;
char *copy_a = (size <= sizeof buf ? buf : xmalloc (size));
char *copy_b = copy_a + lena + 1;
size_t new_len_a, new_len_b, i;
/* Ignore and/or translate chars before comparing. */
for (new_len_a = new_len_b = i = 0; i < MAX (lena, lenb); i++)
{
if (i < lena)
{
copy_a[new_len_a] = (translate
? translate[to_uchar (texta[i])]
: texta[i]);
if (!ignore || !ignore[to_uchar (texta[i])])
++new_len_a;
}
if (i < lenb)
{
copy_b[new_len_b] = (translate
? translate[to_uchar (textb[i])]
: textb [i]);
if (!ignore || !ignore[to_uchar (textb[i])])
++new_len_b;
}
}
diff = xmemcoll (copy_a, new_len_a, copy_b, new_len_b);
if (sizeof buf < size)
free (copy_a);
}
else if (lena == 0)
diff = - NONZERO (lenb);
else if (lenb == 0)
goto greater;
else
diff = xmemcoll (texta, lena, textb, lenb);
}
else if (ignore)
{
char *savea = texta;
#define CMP_WITH_IGNORE(A, B) \
do \
{ \
while (true) \
{ \
while (texta < lima && ignore[to_uchar (*texta)]) \
++texta; \
while (textb < limb && ignore[to_uchar (*textb)]) \
++textb; \
if (! (texta < lima && textb < limb)) \
break; \
diff = to_uchar (A) - to_uchar (B); \
if (diff) \
goto not_equal; \
++texta; \
++textb; \
} \
\
diff = (texta < lima) - (textb < limb); \
} \
while (0)
if (translate)
CMP_WITH_IGNORE (translate[to_uchar (*texta)],
translate[to_uchar (*textb)]);
else
CMP_WITH_IGNORE (*texta, *textb);
/* We only need to restore this for debug_key
in which case the keys being compared are equal. */
texta = savea;
}
else if (lena == 0)
diff = - NONZERO (lenb);
else if (lenb == 0)
goto greater;
else
{
if (translate)
{
char *savea = texta;
while (texta < lima && textb < limb)
{
diff = (to_uchar (translate[to_uchar (*texta++)])
- to_uchar (translate[to_uchar (*textb++)]));
if (diff)
goto not_equal;
}
/* We only need to restore this for debug_key
in which case the keys being compared are equal. */
texta = savea;
}
else
{
diff = memcmp (texta, textb, MIN (lena, lenb));
if (diff)
goto not_equal;
}
diff = lena < lenb ? -1 : lena != lenb;
}
if (diff)
goto not_equal;
if (show_debug)
debug_key (a->text, texta, lima, lena, skipb);
key = key->next;
if (! key)
break;
/* Find the beginning and limit of the next field. */
if (key->eword != SIZE_MAX)
lima = limfield (a, key), limb = limfield (b, key);
else
lima = a->text + a->length - 1, limb = b->text + b->length - 1;
if (key->sword != SIZE_MAX)
texta = begfield (a, key), textb = begfield (b, key);
else
{
texta = a->text, textb = b->text;
if (key->skipsblanks)
{
while (texta < lima && blanks[to_uchar (*texta)])
++texta;
while (textb < limb && blanks[to_uchar (*textb)])
++textb;
}
}
}
return 0;
greater:
diff = 1;
not_equal:
return key->reverse ? -diff : diff;
}
/* Compare two lines A and B, returning negative, zero, or positive
depending on whether A compares less than, equal to, or greater than B. */
static int
compare (const struct line *a, const struct line *b, bool show_debug)
{
int diff;
size_t alen, blen;
/* First try to compare on the specified keys (if any).
The only two cases with no key at all are unadorned sort,
and unadorned sort -r. */
if (keylist)
{
diff = keycompare (a, b, show_debug);
if (diff || unique || stable)
return diff;
}
/* If the keys all compare equal (or no keys were specified)
fall through to the default comparison. */
alen = a->length - 1, blen = b->length - 1;
if (show_debug)
debug_key (a->text, a->text, a->text + alen, alen, false);
if (alen == 0)
diff = - NONZERO (blen);
else if (blen == 0)
diff = 1;
else if (hard_LC_COLLATE)
{
/* Note xmemcoll0 is a performance enhancement as
it will not unconditionally write '\0' after the
passed in buffers, which was seen to give around
a 3% increase in performance for short lines. */
diff = xmemcoll0 (a->text, alen + 1, b->text, blen + 1);
}
else if (! (diff = memcmp (a->text, b->text, MIN (alen, blen))))
diff = alen < blen ? -1 : alen != blen;
return reverse ? -diff : diff;
}
static void
write_bytes (struct line const *line, FILE *fp, char const *output_file)
{
char *buf = line->text;
size_t n_bytes = line->length;
*(buf + n_bytes - 1) = eolchar;
/* Convert TABs to '>' and \0 to \n when -z specified. */
if (debug && fp == stdout)
{
char const *ebuf = buf + n_bytes;
char const *c = buf;
while (c < ebuf)
{
char wc = *c++;
if (wc == '\t')
wc = '>';
else if (wc == 0 && eolchar == 0)
wc = '\n';
if (fputc (wc, fp) == EOF)
die (_("write failed"), output_file);
}
compare (line, line, true);
}
else
{
if (fwrite (buf, 1, n_bytes, fp) != n_bytes)
die (_("write failed"), output_file);
}
}
/* Check that the lines read from FILE_NAME come in order. Return
true if they are in order. If CHECKONLY == 'c', also print a
diagnostic (FILE_NAME, line number, contents of line) to stderr if
they are not in order. */
static bool
check (char const *file_name, char checkonly)
{
FILE *fp = xfopen (file_name, "r");
struct buffer buf; /* Input buffer. */
struct line temp; /* Copy of previous line. */
size_t alloc = 0;
uintmax_t line_number = 0;
struct keyfield const *key = keylist;
bool nonunique = ! unique;
bool ordered = true;
initbuf (&buf, sizeof (struct line),
MAX (merge_buffer_size, sort_size));
temp.text = NULL;
while (fillbuf (&buf, fp, file_name))
{
struct line const *line = buffer_linelim (&buf);
struct line const *linebase = line - buf.nlines;
/* Make sure the line saved from the old buffer contents is
less than or equal to the first line of the new buffer. */
if (alloc && nonunique <= compare (&temp, line - 1, false))
{
found_disorder:
{
if (checkonly == 'c')
{
struct line const *disorder_line = line - 1;
uintmax_t disorder_line_number =
buffer_linelim (&buf) - disorder_line + line_number;
char hr_buf[INT_BUFSIZE_BOUND (disorder_line_number)];
fprintf (stderr, _("%s: %s:%s: disorder: "),
program_name, file_name,
umaxtostr (disorder_line_number, hr_buf));
if (debug)
fputc ('\n', stderr);
write_bytes (disorder_line, debug ? stdout : stderr,
debug ? _("standard out") : _("standard error"));
}
ordered = false;
break;
}
}
/* Compare each line in the buffer with its successor. */
while (linebase < --line)
if (nonunique <= compare (line, line - 1, false))
goto found_disorder;
line_number += buf.nlines;
/* Save the last line of the buffer. */
if (alloc < line->length)
{
do
{
alloc *= 2;
if (! alloc)
{
alloc = line->length;
break;
}
}
while (alloc < line->length);
temp.text = xrealloc (temp.text, alloc);
}
memcpy (temp.text, line->text, line->length);
temp.length = line->length;
if (key)
{
temp.keybeg = temp.text + (line->keybeg - line->text);
temp.keylim = temp.text + (line->keylim - line->text);
}
}
xfclose (fp, file_name);
free (buf.buf);
free (temp.text);
return ordered;
}
/* Open FILES (there are NFILES of them) and store the resulting array
of stream pointers into (*PFPS). Allocate the array. Return the
number of successfully opened files, setting errno if this value is
less than NFILES. */
static size_t
open_input_files (struct sortfile *files, size_t nfiles, FILE ***pfps)
{
FILE **fps = *pfps = xnmalloc (nfiles, sizeof *fps);
int i;
/* Open as many input files as we can. */
for (i = 0; i < nfiles; i++)
{
fps[i] = (files[i].pid
? open_temp (files[i].name, files[i].pid)
: stream_open (files[i].name, "r"));
if (!fps[i])
break;
}
return i;
}
/* Merge lines from FILES onto OFP. NTEMPS is the number of temporary
files (all of which are at the start of the FILES array), and
NFILES is the number of files; 0 <= NTEMPS <= NFILES <= NMERGE.
FPS is the vector of open stream corresponding to the files.
Close input and output streams before returning.
OUTPUT_FILE gives the name of the output file. If it is NULL,
the output file is standard output. */
static void
mergefps (struct sortfile *files, size_t ntemps, size_t nfiles,
FILE *ofp, char const *output_file, FILE **fps)
{
struct buffer *buffer = xnmalloc (nfiles, sizeof *buffer);
/* Input buffers for each file. */
struct line saved; /* Saved line storage for unique check. */
struct line const *savedline = NULL;
/* &saved if there is a saved line. */
size_t savealloc = 0; /* Size allocated for the saved line. */
struct line const **cur = xnmalloc (nfiles, sizeof *cur);
/* Current line in each line table. */
struct line const **base = xnmalloc (nfiles, sizeof *base);
/* Base of each line table. */
size_t *ord = xnmalloc (nfiles, sizeof *ord);
/* Table representing a permutation of fps,
such that cur[ord[0]] is the smallest line
and will be next output. */
size_t i;
size_t j;
size_t t;
struct keyfield const *key = keylist;
saved.text = NULL;
/* Read initial lines from each input file. */
for (i = 0; i < nfiles; )
{
initbuf (&buffer[i], sizeof (struct line),
MAX (merge_buffer_size, sort_size / nfiles));
if (fillbuf (&buffer[i], fps[i], files[i].name))
{
struct line const *linelim = buffer_linelim (&buffer[i]);
cur[i] = linelim - 1;
base[i] = linelim - buffer[i].nlines;
i++;
}
else
{
/* fps[i] is empty; eliminate it from future consideration. */
xfclose (fps[i], files[i].name);
if (i < ntemps)
{
ntemps--;
zaptemp (files[i].name);
}
free (buffer[i].buf);
--nfiles;
for (j = i; j < nfiles; ++j)
{
files[j] = files[j + 1];
fps[j] = fps[j + 1];
}
}
}
/* Set up the ord table according to comparisons among input lines.
Since this only reorders two items if one is strictly greater than
the other, it is stable. */
for (i = 0; i < nfiles; ++i)
ord[i] = i;
for (i = 1; i < nfiles; ++i)
if (0 < compare (cur[ord[i - 1]], cur[ord[i]], false))
t = ord[i - 1], ord[i - 1] = ord[i], ord[i] = t, i = 0;
/* Repeatedly output the smallest line until no input remains. */
while (nfiles)
{
struct line const *smallest = cur[ord[0]];
/* If uniquified output is turned on, output only the first of
an identical series of lines. */
if (unique)
{
if (savedline && compare (savedline, smallest, false))
{
savedline = NULL;
write_bytes (&saved, ofp, output_file);
}
if (!savedline)
{
savedline = &saved;
if (savealloc < smallest->length)
{
do
if (! savealloc)
{
savealloc = smallest->length;
break;
}
while ((savealloc *= 2) < smallest->length);
saved.text = xrealloc (saved.text, savealloc);
}
saved.length = smallest->length;
memcpy (saved.text, smallest->text, saved.length);
if (key)
{
saved.keybeg =
saved.text + (smallest->keybeg - smallest->text);
saved.keylim =
saved.text + (smallest->keylim - smallest->text);
}
}
}
else
write_bytes (smallest, ofp, output_file);
/* Check if we need to read more lines into core. */
if (base[ord[0]] < smallest)
cur[ord[0]] = smallest - 1;
else
{
if (fillbuf (&buffer[ord[0]], fps[ord[0]], files[ord[0]].name))
{
struct line const *linelim = buffer_linelim (&buffer[ord[0]]);
cur[ord[0]] = linelim - 1;
base[ord[0]] = linelim - buffer[ord[0]].nlines;
}
else
{
/* We reached EOF on fps[ord[0]]. */
for (i = 1; i < nfiles; ++i)
if (ord[i] > ord[0])
--ord[i];
--nfiles;
xfclose (fps[ord[0]], files[ord[0]].name);
if (ord[0] < ntemps)
{
ntemps--;
zaptemp (files[ord[0]].name);
}
free (buffer[ord[0]].buf);
for (i = ord[0]; i < nfiles; ++i)
{
fps[i] = fps[i + 1];
files[i] = files[i + 1];
buffer[i] = buffer[i + 1];
cur[i] = cur[i + 1];
base[i] = base[i + 1];
}
for (i = 0; i < nfiles; ++i)
ord[i] = ord[i + 1];
continue;
}
}
/* The new line just read in may be larger than other lines
already in main memory; push it back in the queue until we
encounter a line larger than it. Optimize for the common
case where the new line is smallest. */
{
size_t lo = 1;
size_t hi = nfiles;
size_t probe = lo;
size_t ord0 = ord[0];
size_t count_of_smaller_lines;
while (lo < hi)
{
int cmp = compare (cur[ord0], cur[ord[probe]], false);
if (cmp < 0 || (cmp == 0 && ord0 < ord[probe]))
hi = probe;
else
lo = probe + 1;
probe = (lo + hi) / 2;
}
count_of_smaller_lines = lo - 1;
for (j = 0; j < count_of_smaller_lines; j++)
ord[j] = ord[j + 1];
ord[count_of_smaller_lines] = ord0;
}
/* Free up some resources every once in a while. */
if (MAX_PROCS_BEFORE_REAP < nprocs)
reap_some ();
}
if (unique && savedline)
{
write_bytes (&saved, ofp, output_file);
free (saved.text);
}
xfclose (ofp, output_file);
free (fps);
free (buffer);
free (ord);
free (base);
free (cur);
}
/* Merge lines from FILES onto OFP. NTEMPS is the number of temporary
files (all of which are at the start of the FILES array), and
NFILES is the number of files; 0 <= NTEMPS <= NFILES <= NMERGE.
Close input and output files before returning.
OUTPUT_FILE gives the name of the output file.
Return the number of files successfully merged. This number can be
less than NFILES if we ran low on file descriptors, but in this
case it is never less than 2. */
static size_t
mergefiles (struct sortfile *files, size_t ntemps, size_t nfiles,
FILE *ofp, char const *output_file)
{
FILE **fps;
size_t nopened = open_input_files (files, nfiles, &fps);
if (nopened < nfiles && nopened < 2)
die (_("open failed"), files[nopened].name);
mergefps (files, ntemps, nopened, ofp, output_file, fps);
return nopened;
}
/* Merge into T (of size NLINES) the two sorted arrays of lines
LO (with NLINES / 2 members), and
T - (NLINES / 2) (with NLINES - NLINES / 2 members).
T and LO point just past their respective arrays, and the arrays
are in reverse order. NLINES must be at least 2. */
static inline void
mergelines (struct line *restrict t, size_t nlines,
struct line const *restrict lo)
{
size_t nlo = nlines / 2;
size_t nhi = nlines - nlo;
struct line *hi = t - nlo;
while (true)
if (compare (lo - 1, hi - 1, false) <= 0)
{
*--t = *--lo;
if (! --nlo)
{
/* HI must equal T now, and there is no need to copy from
HI to T. */
return;
}
}
else
{
*--t = *--hi;
if (! --nhi)
{
do
*--t = *--lo;
while (--nlo);
return;
}
}
}
/* Sort the array LINES with NLINES members, using TEMP for temporary space.
NLINES must be at least 2.
The input and output arrays are in reverse order, and LINES and
TEMP point just past the end of their respective arrays.
Use a recursive divide-and-conquer algorithm, in the style
suggested by Knuth volume 3 (2nd edition), exercise 5.2.4-23. Use
the optimization suggested by exercise 5.2.4-10; this requires room
for only 1.5*N lines, rather than the usual 2*N lines. Knuth
writes that this memory optimization was originally published by
D. A. Bell, Comp J. 1 (1958), 75. */
static void
sequential_sort (struct line *restrict lines, size_t nlines,
struct line *restrict temp, bool to_temp)
{
if (nlines == 2)
{
/* Declare `swap' as int, not bool, to work around a bug
<http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html>
in the IBM xlc 6.0.0.0 compiler in 64-bit mode. */
int swap = (0 < compare (&lines[-1], &lines[-2], false));
if (to_temp)
{
temp[-1] = lines[-1 - swap];
temp[-2] = lines[-2 + swap];
}
else if (swap)
{
temp[-1] = lines[-1];
lines[-1] = lines[-2];
lines[-2] = temp[-1];
}
}
else
{
size_t nlo = nlines / 2;
size_t nhi = nlines - nlo;
struct line *lo = lines;
struct line *hi = lines - nlo;
sequential_sort (hi, nhi, temp - (to_temp ? nlo : 0), to_temp);
if (1 < nlo)
sequential_sort (lo, nlo, temp, !to_temp);
else if (!to_temp)
temp[-1] = lo[-1];
struct line *dest;
struct line const *sorted_lo;
if (to_temp)
{
dest = temp;
sorted_lo = lines;
}
else
{
dest = lines;
sorted_lo = temp;
}
mergelines (dest, nlines, sorted_lo);
}
}
/* Compare two NODEs for priority. The NODE with the higher (numerically
lower) level has priority. If tie, the NODE with the most remaining
lines has priority. */
static int
compare_nodes (const void *a, const void *b)
{
const struct merge_node *nodea = (const struct merge_node *) a;
const struct merge_node *nodeb = (const struct merge_node *) b;
if (nodea->level == nodeb->level)
return (nodea->nlo + nodea->nhi) < (nodeb->nlo + nodeb->nhi);
return nodea->level < nodeb->level;
}
/* Lock a merge tree NODE.
Note spin locks were seen to perform better than mutexes
as long as the number of threads is limited to the
number of processors. */
static inline void
lock_node (struct merge_node *const restrict node)
{
pthread_spin_lock (node->lock);
}
/* Unlock a merge tree NODE. */
static inline void
unlock_node (struct merge_node *const restrict node)
{
pthread_spin_unlock (node->lock);
}
/* Destroy merge QUEUE. */
static inline void
queue_destroy (struct merge_node_queue *const restrict queue)
{
heap_free (queue->priority_queue);
pthread_cond_destroy (&queue->cond);
pthread_mutex_destroy (&queue->mutex);
}
/* Initialize merge QUEUE, allocating space for a maximum of RESERVE nodes.
Though it's highly unlikely all nodes are in the heap at the same time,
RESERVE should accommodate all of them. Counting a NULL dummy head for the
heap, RESERVE should be 2 * NTHREADS. */
static inline void
queue_init (struct merge_node_queue *const restrict queue, size_t reserve)
{
queue->priority_queue = (struct heap *) heap_alloc (compare_nodes, reserve);
pthread_mutex_init (&queue->mutex, NULL);
pthread_cond_init (&queue->cond, NULL);
}
/* Insert NODE into priority QUEUE. Assume caller either holds lock on NODE
or does not need to lock NODE. */
static inline void
queue_insert (struct merge_node_queue *const restrict queue,
struct merge_node *const restrict node)
{
pthread_mutex_lock (&queue->mutex);
heap_insert (queue->priority_queue, node);
node->queued = true;
pthread_mutex_unlock (&queue->mutex);
pthread_cond_signal (&queue->cond);
}
/* Pop NODE off priority QUEUE. Guarantee a non-null, spinlocked NODE. */
static inline struct merge_node *
queue_pop (struct merge_node_queue *const restrict queue)
{
struct merge_node *node = NULL;
while (!node)
{
pthread_mutex_lock (&queue->mutex);
if (queue->priority_queue->count)
node = (struct merge_node *) heap_remove_top (queue->priority_queue);
else
{
/* Go into conditional wait if no NODE is immediately available. */
pthread_cond_wait (&queue->cond, &queue->mutex);
}
pthread_mutex_unlock (&queue->mutex);
}
lock_node (node);
node->queued = false;
return node;
}
/* If UNQIUE is set, checks to make sure line isn't a duplicate before
outputting. If UNIQUE is not set, output the passed in line. Note that
this function does not actually save the line, nor any key information,
thus is only appropriate for internal sort. */
static inline void
write_unique (struct line *const restrict line, FILE *tfp,
const char *temp_output)
{
static struct line *saved = NULL;
if (!unique)
write_bytes (line, tfp, temp_output);
else if (!saved || compare (line, saved, false))
{
saved = line;
write_bytes (line, tfp, temp_output);
}
}
/* Merge the lines currently available to a NODE in the binary
merge tree, up to a maximum specified by MAX_MERGE. */
static inline size_t
mergelines_node (struct merge_node *const restrict node, size_t total_lines,
FILE *tfp, const char *temp_output)
{
struct line *lo_orig = node->lo;
struct line *hi_orig = node->hi;
size_t to_merge = MAX_MERGE (total_lines, node->level);
size_t merged_lo;
size_t merged_hi;
if (node->level > MERGE_ROOT)
{
/* Merge to destination buffer. */
struct line *dest = *node->dest;
while (node->lo != node->end_lo && node->hi != node->end_hi && to_merge--)
if (compare (node->lo - 1, node->hi - 1, false) <= 0)
*--dest = *--node->lo;
else
*--dest = *--node->hi;
merged_lo = lo_orig - node->lo;
merged_hi = hi_orig - node->hi;
if (node->nhi == merged_hi)
while (node->lo != node->end_lo && to_merge--)
*--dest = *--node->lo;
else if (node->nlo == merged_lo)
while (node->hi != node->end_hi && to_merge--)
*--dest = *--node->hi;
}
else
{
/* Merge directly to output. */
while (node->lo != node->end_lo && node->hi != node->end_hi && to_merge--)
{
if (compare (node->lo - 1, node->hi - 1, false) <= 0)
write_unique (--node->lo, tfp, temp_output);
else
write_unique (--node->hi, tfp, temp_output);
}
merged_lo = lo_orig - node->lo;
merged_hi = hi_orig - node->hi;
if (node->nhi == merged_hi)
{
while (node->lo != node->end_lo && to_merge--)
write_unique (--node->lo, tfp, temp_output);
}
else if (node->nlo == merged_lo)
{
while (node->hi != node->end_hi && to_merge--)
write_unique (--node->hi, tfp, temp_output);
}
node->dest -= lo_orig - node->lo + hi_orig - node->hi;
}
/* Update NODE. */
merged_lo = lo_orig - node->lo;
merged_hi = hi_orig - node->hi;
node->nlo -= merged_lo;
node->nhi -= merged_hi;
return merged_lo + merged_hi;
}
/* Insert NODE into QUEUE if it passes insertion checks. */
static inline void
check_insert (struct merge_node *node,
struct merge_node_queue *const restrict queue)
{
size_t lo_avail = node->lo - node->end_lo;
size_t hi_avail = node->hi - node->end_hi;
/* Conditions for insertion:
1. NODE is not already in heap.
2. NODE has available lines from both it's children, OR one child has
available lines, but the other has exhausted all its lines. */
if ((!node->queued)
&& ((lo_avail && (hi_avail || !(node->nhi)))
|| (hi_avail && !(node->nlo))))
{
queue_insert (queue, node);
}
}
/* Update parent merge tree NODE. */
static inline void
update_parent (struct merge_node *const restrict node, size_t merged,
struct merge_node_queue *const restrict queue)
{
if (node->level > MERGE_ROOT)
{
lock_node (node->parent);
*node->dest -= merged;
check_insert (node->parent, queue);
unlock_node (node->parent);
}
else if (node->nlo + node->nhi == 0)
{
/* If the MERGE_ROOT NODE has finished merging, insert the
MERGE_END node. */
queue_insert (queue, node->parent);
}
}
/* Repeatedly pop QUEUE for a NODE with lines to merge, and merge at least
some of those lines, until the MERGE_END node is popped. */
static void
merge_loop (struct merge_node_queue *const restrict queue,
const size_t total_lines, FILE *tfp, const char *temp_output)
{
while (1)
{
struct merge_node *node = queue_pop (queue);
if (node->level == MERGE_END)
{
unlock_node (node);
/* Reinsert so other threads can pop it. */
queue_insert (queue, node);
break;
}
size_t merged_lines = mergelines_node (node, total_lines, tfp,
temp_output);
check_insert (node, queue);
update_parent (node, merged_lines, queue);
unlock_node (node);
}
}
static void sortlines (struct line *restrict, struct line *restrict,
unsigned long int, const size_t,
struct merge_node *const restrict, bool,
struct merge_node_queue *const restrict,
FILE *, const char *);
/* Thread arguments for sortlines_thread. */
struct thread_args
{
struct line *lines;
struct line *dest;
unsigned long int nthreads;
const size_t total_lines;
struct merge_node *const restrict parent;
bool lo_child;
struct merge_node_queue *const restrict merge_queue;
FILE *tfp;
const char *output_temp;
};
/* Like sortlines, except with a signature acceptable to pthread_create. */
static void *
sortlines_thread (void *data)
{
struct thread_args const *args = data;
sortlines (args->lines, args->dest, args->nthreads, args->total_lines,
args->parent, args->lo_child, args->merge_queue,
args->tfp, args->output_temp);
return NULL;
}
/* There are three phases to the algorithm: node creation, sequential sort,
and binary merge.
During node creation, sortlines recursively visits each node in the
binary merge tree and creates a NODE structure corresponding to all the
future line merging NODE is responsible for. For each call to
sortlines, half the available threads are assigned to each recursive
call, until a leaf node having only 1 available thread is reached.
Each leaf node then performs two sequential sorts, one on each half of
the lines it is responsible for. It records in its NODE structure that
there are two sorted sublists available to merge from, and inserts its
NODE into the priority queue.
The binary merge phase then begins. Each thread drops into a loop
where the thread retrieves a NODE from the priority queue, merges lines
available to that NODE, and potentially insert NODE or its parent back
into the queue if there are sufficient available lines for them to
merge. This continues until all lines at all nodes of the merge tree
have been merged. */
static void
sortlines (struct line *restrict lines, struct line *restrict dest,
unsigned long int nthreads, const size_t total_lines,
struct merge_node *const restrict parent, bool lo_child,
struct merge_node_queue *const restrict merge_queue,
FILE *tfp, const char *temp_output)
{
/* Create merge tree NODE. */
size_t nlines = (lo_child)? parent->nlo : parent->nhi;
size_t nlo = nlines / 2;
size_t nhi = nlines - nlo;
struct line *lo = dest - total_lines;
struct line *hi = lo - nlo;
struct line **parent_end = (lo_child)? &parent->end_lo : &parent->end_hi;
pthread_spinlock_t lock;
pthread_spin_init (&lock, PTHREAD_PROCESS_PRIVATE);
struct merge_node node = {lo, hi, lo, hi, parent_end, nlo, nhi,
parent->level + 1, parent, false, &lock};
/* Calculate thread arguments. */
unsigned long int lo_threads = nthreads / 2;
unsigned long int hi_threads = nthreads - lo_threads;
pthread_t thread;
struct thread_args args = {lines, lo, lo_threads, total_lines, &node,
true, merge_queue, tfp, temp_output};
if (nthreads > 1 && SUBTHREAD_LINES_HEURISTIC <= nlines
&& pthread_create (&thread, NULL, sortlines_thread, &args) == 0)
{
sortlines (lines - nlo, hi, hi_threads, total_lines, &node, false,
merge_queue, tfp, temp_output);
pthread_join (thread, NULL);
}
else
{
/* Nthreads = 1, this is a leaf NODE, or pthread_create failed.
Sort with 1 thread. */
struct line *temp = lines - total_lines;
if (1 < nhi)
sequential_sort (lines - nlo, nhi, temp - nlo / 2, false);
if (1 < nlo)
sequential_sort (lines, nlo, temp, false);
/* Update merge NODE. No need to lock yet. */
node.lo = lines;
node.hi = lines - nlo;
node.end_lo = lines - nlo;
node.end_hi = lines - nlo - nhi;
queue_insert (merge_queue, &node);
merge_loop (merge_queue, total_lines, tfp, temp_output);
}
}
/* Scan through FILES[NTEMPS .. NFILES-1] looking for a file that is
the same as OUTFILE. If found, merge the found instances (and perhaps
some other files) into a temporary file so that it can in turn be
merged into OUTFILE without destroying OUTFILE before it is completely
read. Return the new value of NFILES, which differs from the old if
some merging occurred.
This test ensures that an otherwise-erroneous use like
"sort -m -o FILE ... FILE ..." copies FILE before writing to it.
It's not clear that POSIX requires this nicety.
Detect common error cases, but don't try to catch obscure cases like
"cat ... FILE ... | sort -m -o FILE"
where traditional "sort" doesn't copy the input and where
people should know that they're getting into trouble anyway.
Catching these obscure cases would slow down performance in
common cases. */
static size_t
avoid_trashing_input (struct sortfile *files, size_t ntemps,
size_t nfiles, char const *outfile)
{
size_t i;
bool got_outstat = false;
struct stat outstat;
for (i = ntemps; i < nfiles; i++)
{
bool is_stdin = STREQ (files[i].name, "-");
bool same;
struct stat instat;
if (outfile && STREQ (outfile, files[i].name) && !is_stdin)
same = true;
else
{
if (! got_outstat)
{
if ((outfile
? stat (outfile, &outstat)
: fstat (STDOUT_FILENO, &outstat))
!= 0)
break;
got_outstat = true;
}
same = (((is_stdin
? fstat (STDIN_FILENO, &instat)
: stat (files[i].name, &instat))
== 0)
&& SAME_INODE (instat, outstat));
}
if (same)
{
FILE *tftp;
pid_t pid;
char *temp = create_temp (&tftp, &pid);
size_t num_merged = 0;
do
{
num_merged += mergefiles (&files[i], 0, nfiles - i, tftp, temp);
files[i].name = temp;
files[i].pid = pid;
if (i + num_merged < nfiles)
memmove (&files[i + 1], &files[i + num_merged],
num_merged * sizeof *files);
ntemps += 1;
nfiles -= num_merged - 1;;
i += num_merged;
}
while (i < nfiles);
}
}
return nfiles;
}
/* Merge the input FILES. NTEMPS is the number of files at the
start of FILES that are temporary; it is zero at the top level.
NFILES is the total number of files. Put the output in
OUTPUT_FILE; a null OUTPUT_FILE stands for standard output. */
static void
merge (struct sortfile *files, size_t ntemps, size_t nfiles,
char const *output_file)
{
while (nmerge < nfiles)
{
/* Number of input files processed so far. */
size_t in;
/* Number of output files generated so far. */
size_t out;
/* nfiles % NMERGE; this counts input files that are left over
after all full-sized merges have been done. */
size_t remainder;
/* Number of easily-available slots at the next loop iteration. */
size_t cheap_slots;
/* Do as many NMERGE-size merges as possible. In the case that
nmerge is bogus, increment by the maximum number of file
descriptors allowed. */
for (out = in = 0; nmerge <= nfiles - in; out++)
{
FILE *tfp;
pid_t pid;
char *temp = create_temp (&tfp, &pid);
size_t num_merged = mergefiles (&files[in], MIN (ntemps, nmerge),
nmerge, tfp, temp);
ntemps -= MIN (ntemps, num_merged);
files[out].name = temp;
files[out].pid = pid;
in += num_merged;
}
remainder = nfiles - in;
cheap_slots = nmerge - out % nmerge;
if (cheap_slots < remainder)
{
/* So many files remain that they can't all be put into the last
NMERGE-sized output window. Do one more merge. Merge as few
files as possible, to avoid needless I/O. */
size_t nshortmerge = remainder - cheap_slots + 1;
FILE *tfp;
pid_t pid;
char *temp = create_temp (&tfp, &pid);
size_t num_merged = mergefiles (&files[in], MIN (ntemps, nshortmerge),
nshortmerge, tfp, temp);
ntemps -= MIN (ntemps, num_merged);
files[out].name = temp;
files[out++].pid = pid;
in += num_merged;
}
/* Put the remaining input files into the last NMERGE-sized output
window, so they will be merged in the next pass. */
memmove (&files[out], &files[in], (nfiles - in) * sizeof *files);
ntemps += out;
nfiles -= in - out;
}
nfiles = avoid_trashing_input (files, ntemps, nfiles, output_file);
/* We aren't guaranteed that this final mergefiles will work, therefore we
try to merge into the output, and then merge as much as we can into a
temp file if we can't. Repeat. */
while (true)
{
/* Merge directly into the output file if possible. */
FILE **fps;
size_t nopened = open_input_files (files, nfiles, &fps);
if (nopened == nfiles)
{
FILE *ofp = stream_open (output_file, "w");
if (ofp)
{
mergefps (files, ntemps, nfiles, ofp, output_file, fps);
break;
}
if (errno != EMFILE || nopened <= 2)
die (_("open failed"), output_file);
}
else if (nopened <= 2)
die (_("open failed"), files[nopened].name);
/* We ran out of file descriptors. Close one of the input
files, to gain a file descriptor. Then create a temporary
file with our spare file descriptor. Retry if that failed
(e.g., some other process could open a file between the time
we closed and tried to create). */
FILE *tfp;
pid_t pid;
char *temp;
do
{
nopened--;
xfclose (fps[nopened], files[nopened].name);
temp = maybe_create_temp (&tfp, &pid, ! (nopened <= 2));
}
while (!temp);
/* Merge into the newly allocated temporary. */
mergefps (&files[0], MIN (ntemps, nopened), nopened, tfp, temp, fps);
ntemps -= MIN (ntemps, nopened);
files[0].name = temp;
files[0].pid = pid;
memmove (&files[1], &files[nopened], (nfiles - nopened) * sizeof *files);
ntemps++;
nfiles -= nopened - 1;
}
}
/* Sort NFILES FILES onto OUTPUT_FILE. */
static void
sort (char * const *files, size_t nfiles, char const *output_file,
unsigned long int nthreads)
{
struct buffer buf;
size_t ntemps = 0;
bool output_file_created = false;
buf.alloc = 0;
while (nfiles)
{
char const *temp_output;
char const *file = *files;
FILE *fp = xfopen (file, "r");
FILE *tfp;
size_t bytes_per_line;
if (nthreads > 1)
{
/* Get log P. */
unsigned long int tmp = 1;
size_t mult = 1;
while (tmp < nthreads)
{
tmp *= 2;
mult++;
}
bytes_per_line = (mult * sizeof (struct line));
}
else
bytes_per_line = sizeof (struct line) * 3 / 2;
if (! buf.alloc)
initbuf (&buf, bytes_per_line,
sort_buffer_size (&fp, 1, files, nfiles, bytes_per_line));
buf.eof = false;
files++;
nfiles--;
while (fillbuf (&buf, fp, file))
{
struct line *line;
if (buf.eof && nfiles
&& (bytes_per_line + 1
< (buf.alloc - buf.used - bytes_per_line * buf.nlines)))
{
/* End of file, but there is more input and buffer room.
Concatenate the next input file; this is faster in
the usual case. */
buf.left = buf.used;
break;
}
line = buffer_linelim (&buf);
if (buf.eof && !nfiles && !ntemps && !buf.left)
{
xfclose (fp, file);
tfp = xfopen (output_file, "w");
temp_output = output_file;
output_file_created = true;
}
else
{
++ntemps;
temp_output = create_temp (&tfp, NULL);
}
if (1 < buf.nlines)
{
struct merge_node_queue merge_queue;
queue_init (&merge_queue, 2 * nthreads);
pthread_spinlock_t lock;
pthread_spin_init (&lock, PTHREAD_PROCESS_PRIVATE);
struct merge_node node =
{NULL, NULL, NULL, NULL, NULL, buf.nlines,
buf.nlines, MERGE_END, NULL, false, &lock};
sortlines (line, line, nthreads, buf.nlines, &node, true,
&merge_queue, tfp, temp_output);
queue_destroy (&merge_queue);
}
else
write_unique (line - 1, tfp, temp_output);
xfclose (tfp, temp_output);
/* Free up some resources every once in a while. */
if (MAX_PROCS_BEFORE_REAP < nprocs)
reap_some ();
if (output_file_created)
goto finish;
}
xfclose (fp, file);
}
finish:
free (buf.buf);
if (! output_file_created)
{
size_t i;
struct tempnode *node = temphead;
struct sortfile *tempfiles = xnmalloc (ntemps, sizeof *tempfiles);
for (i = 0; node; i++)
{
tempfiles[i].name = node->name;
tempfiles[i].pid = node->pid;
node = node->next;
}
merge (tempfiles, ntemps, ntemps, output_file);
free (tempfiles);
}
}
/* Insert a malloc'd copy of key KEY_ARG at the end of the key list. */
static void
insertkey (struct keyfield *key_arg)
{
struct keyfield **p;
struct keyfield *key = xmemdup (key_arg, sizeof *key);
for (p = &keylist; *p; p = &(*p)->next)
continue;
*p = key;
key->next = NULL;
}
/* Report a bad field specification SPEC, with extra info MSGID. */
static void badfieldspec (char const *, char const *)
ATTRIBUTE_NORETURN;
static void
badfieldspec (char const *spec, char const *msgid)
{
error (SORT_FAILURE, 0, _("%s: invalid field specification %s"),
_(msgid), quote (spec));
abort ();
}
/* Report incompatible options. */
static void incompatible_options (char const *) ATTRIBUTE_NORETURN;
static void
incompatible_options (char const *opts)
{
error (SORT_FAILURE, 0, _("options `-%s' are incompatible"), opts);
abort ();
}
/* Check compatibility of ordering options. */
static void
check_ordering_compatibility (void)
{
struct keyfield *key;
for (key = keylist; key; key = key->next)
if ((1 < (key->random + key->numeric + key->general_numeric + key->month
+ key->version + !!key->ignore + key->human_numeric))
|| (key->random && key->translate))
{
/* The following is too big, but guaranteed to be "big enough". */
char opts[sizeof short_options];
/* Clear flags we're not interested in. */
key->skipsblanks = key->skipeblanks = key->reverse = false;
key_to_opts (key, opts);
incompatible_options (opts);
}
}
/* Parse the leading integer in STRING and store the resulting value
(which must fit into size_t) into *VAL. Return the address of the
suffix after the integer. If the value is too large, silently
substitute SIZE_MAX. If MSGID is NULL, return NULL after
failure; otherwise, report MSGID and exit on failure. */
static char const *
parse_field_count (char const *string, size_t *val, char const *msgid)
{
char *suffix;
uintmax_t n;
switch (xstrtoumax (string, &suffix, 10, &n, ""))
{
case LONGINT_OK:
case LONGINT_INVALID_SUFFIX_CHAR:
*val = n;
if (*val == n)
break;
/* Fall through. */
case LONGINT_OVERFLOW:
case LONGINT_OVERFLOW | LONGINT_INVALID_SUFFIX_CHAR:
*val = SIZE_MAX;
break;
case LONGINT_INVALID:
if (msgid)
error (SORT_FAILURE, 0, _("%s: invalid count at start of %s"),
_(msgid), quote (string));
return NULL;
}
return suffix;
}
/* Handle interrupts and hangups. */
static void
sighandler (int sig)
{
if (! SA_NOCLDSTOP)
signal (sig, SIG_IGN);
cleanup ();
signal (sig, SIG_DFL);
raise (sig);
}
/* Set the ordering options for KEY specified in S.
Return the address of the first character in S that
is not a valid ordering option.
BLANKTYPE is the kind of blanks that 'b' should skip. */
static char *
set_ordering (const char *s, struct keyfield *key, enum blanktype blanktype)
{
while (*s)
{
switch (*s)
{
case 'b':
if (blanktype == bl_start || blanktype == bl_both)
key->skipsblanks = true;
if (blanktype == bl_end || blanktype == bl_both)
key->skipeblanks = true;
break;
case 'd':
key->ignore = nondictionary;
break;
case 'f':
key->translate = fold_toupper;
break;
case 'g':
key->general_numeric = true;
break;
case 'h':
key->human_numeric = true;
break;
case 'i':
/* Option order should not matter, so don't let -i override
-d. -d implies -i, but -i does not imply -d. */
if (! key->ignore)
key->ignore = nonprinting;
break;
case 'M':
key->month = true;
break;
case 'n':
key->numeric = true;
break;
case 'R':
key->random = true;
break;
case 'r':
key->reverse = true;
break;
case 'V':
key->version = true;
break;
default:
return (char *) s;
}
++s;
}
return (char *) s;
}
static struct keyfield *
key_init (struct keyfield *key)
{
memset (key, 0, sizeof *key);
key->eword = SIZE_MAX;
key->iec_present = -1;
return key;
}
int
main (int argc, char **argv)
{
struct keyfield *key;
struct keyfield key_buf;
struct keyfield gkey;
bool gkey_only = false;
char const *s;
int c = 0;
char checkonly = 0;
bool mergeonly = false;
char *random_source = NULL;
bool need_random = false;
unsigned long int nthreads = 0;
size_t nfiles = 0;
bool posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
bool obsolete_usage = (posix2_version () < 200112);
char **files;
char *files_from = NULL;
struct Tokens tok;
char const *outfile = NULL;
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
initialize_exit_failure (SORT_FAILURE);
hard_LC_COLLATE = hard_locale (LC_COLLATE);
#if HAVE_NL_LANGINFO
hard_LC_TIME = hard_locale (LC_TIME);
#endif
/* Get locale's representation of the decimal point. */
{
struct lconv const *locale = localeconv ();
/* If the locale doesn't define a decimal point, or if the decimal
point is multibyte, use the C locale's decimal point. FIXME:
add support for multibyte decimal points. */
decimal_point = to_uchar (locale->decimal_point[0]);
if (! decimal_point || locale->decimal_point[1])
decimal_point = '.';
/* FIXME: add support for multibyte thousands separators. */
thousands_sep = to_uchar (*locale->thousands_sep);
if (! thousands_sep || locale->thousands_sep[1])
thousands_sep = -1;
}
have_read_stdin = false;
inittables ();
{
size_t i;
static int const sig[] =
{
/* The usual suspects. */
SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
#ifdef SIGPOLL
SIGPOLL,
#endif
#ifdef SIGPROF
SIGPROF,
#endif
#ifdef SIGVTALRM
SIGVTALRM,
#endif
#ifdef SIGXCPU
SIGXCPU,
#endif
#ifdef SIGXFSZ
SIGXFSZ,
#endif
};
enum { nsigs = ARRAY_CARDINALITY (sig) };
#if SA_NOCLDSTOP
struct sigaction act;
sigemptyset (&caught_signals);
for (i = 0; i < nsigs; i++)
{
sigaction (sig[i], NULL, &act);
if (act.sa_handler != SIG_IGN)
sigaddset (&caught_signals, sig[i]);
}
act.sa_handler = sighandler;
act.sa_mask = caught_signals;
act.sa_flags = 0;
for (i = 0; i < nsigs; i++)
if (sigismember (&caught_signals, sig[i]))
sigaction (sig[i], &act, NULL);
#else
for (i = 0; i < nsigs; i++)
if (signal (sig[i], SIG_IGN) != SIG_IGN)
{
signal (sig[i], sighandler);
siginterrupt (sig[i], 1);
}
#endif
}
signal (SIGCHLD, SIG_DFL); /* Don't inherit CHLD handling from parent. */
/* The signal mask is known, so it is safe to invoke exit_cleanup. */
atexit (exit_cleanup);
key_init (&gkey);
gkey.sword = SIZE_MAX;
files = xnmalloc (argc, sizeof *files);
while (true)
{
/* Parse an operand as a file after "--" was seen; or if
pedantic and a file was seen, unless the POSIX version
predates 1003.1-2001 and -c was not seen and the operand is
"-o FILE" or "-oFILE". */
int oi = -1;
if (c == -1
|| (posixly_correct && nfiles != 0
&& ! (obsolete_usage
&& ! checkonly
&& optind != argc
&& argv[optind][0] == '-' && argv[optind][1] == 'o'
&& (argv[optind][2] || optind + 1 != argc)))
|| ((c = getopt_long (argc, argv, short_options,
long_options, &oi))
== -1))
{
if (argc <= optind)
break;
files[nfiles++] = argv[optind++];
}
else switch (c)
{
case 1:
key = NULL;
if (optarg[0] == '+')
{
bool minus_pos_usage = (optind != argc && argv[optind][0] == '-'
&& ISDIGIT (argv[optind][1]));
obsolete_usage |= minus_pos_usage && !posixly_correct;
if (obsolete_usage)
{
/* Treat +POS1 [-POS2] as a key if possible; but silently
treat an operand as a file if it is not a valid +POS1. */
key = key_init (&key_buf);
s = parse_field_count (optarg + 1, &key->sword, NULL);
if (s && *s == '.')
s = parse_field_count (s + 1, &key->schar, NULL);
if (! (key->sword || key->schar))
key->sword = SIZE_MAX;
if (! s || *set_ordering (s, key, bl_start))
key = NULL;
else
{
if (minus_pos_usage)
{
char const *optarg1 = argv[optind++];
s = parse_field_count (optarg1 + 1, &key->eword,
N_("invalid number after `-'"));
if (*s == '.')
s = parse_field_count (s + 1, &key->echar,
N_("invalid number after `.'"));
if (!key->echar && key->eword)
{
/* obsolescent syntax +A.x -B.y is equivalent to:
-k A+1.x+1,B.y (when y = 0)
-k A+1.x+1,B+1.y (when y > 0)
So eword is decremented as in the -k case
only when the end field (B) is specified and
echar (y) is 0. */
key->eword--;
}
if (*set_ordering (s, key, bl_end))
badfieldspec (optarg1,
N_("stray character in field spec"));
}
key->obsolete_used = true;
insertkey (key);
}
}
}
if (! key)
files[nfiles++] = optarg;
break;
case SORT_OPTION:
c = XARGMATCH ("--sort", optarg, sort_args, sort_types);
/* Fall through. */
case 'b':
case 'd':
case 'f':
case 'g':
case 'h':
case 'i':
case 'M':
case 'n':
case 'r':
case 'R':
case 'V':
{
char str[2];
str[0] = c;
str[1] = '\0';
set_ordering (str, &gkey, bl_both);
}
break;
case CHECK_OPTION:
c = (optarg
? XARGMATCH ("--check", optarg, check_args, check_types)
: 'c');
/* Fall through. */
case 'c':
case 'C':
if (checkonly && checkonly != c)
incompatible_options ("cC");
checkonly = c;
break;
case COMPRESS_PROGRAM_OPTION:
if (compress_program && !STREQ (compress_program, optarg))
error (SORT_FAILURE, 0, _("multiple compress programs specified"));
compress_program = optarg;
break;
case DEBUG_PROGRAM_OPTION:
debug = true;
break;
case FILES0_FROM_OPTION:
files_from = optarg;
break;
case 'k':
key = key_init (&key_buf);
/* Get POS1. */
s = parse_field_count (optarg, &key->sword,
N_("invalid number at field start"));
if (! key->sword--)
{
/* Provoke with `sort -k0' */
badfieldspec (optarg, N_("field number is zero"));
}
if (*s == '.')
{
s = parse_field_count (s + 1, &key->schar,
N_("invalid number after `.'"));
if (! key->schar--)
{
/* Provoke with `sort -k1.0' */
badfieldspec (optarg, N_("character offset is zero"));
}
}
if (! (key->sword || key->schar))
key->sword = SIZE_MAX;
s = set_ordering (s, key, bl_start);
if (*s != ',')
{
key->eword = SIZE_MAX;
key->echar = 0;
}
else
{
/* Get POS2. */
s = parse_field_count (s + 1, &key->eword,
N_("invalid number after `,'"));
if (! key->eword--)
{
/* Provoke with `sort -k1,0' */
badfieldspec (optarg, N_("field number is zero"));
}
if (*s == '.')
{
s = parse_field_count (s + 1, &key->echar,
N_("invalid number after `.'"));
}
s = set_ordering (s, key, bl_end);
}
if (*s)
badfieldspec (optarg, N_("stray character in field spec"));
insertkey (key);
break;
case 'm':
mergeonly = true;
break;
case NMERGE_OPTION:
specify_nmerge (oi, c, optarg);
break;
case 'o':
if (outfile && !STREQ (outfile, optarg))
error (SORT_FAILURE, 0, _("multiple output files specified"));
outfile = optarg;
break;
case RANDOM_SOURCE_OPTION:
if (random_source && !STREQ (random_source, optarg))
error (SORT_FAILURE, 0, _("multiple random sources specified"));
random_source = optarg;
break;
case 's':
stable = true;
break;
case 'S':
specify_sort_size (oi, c, optarg);
break;
case 't':
{
char newtab = optarg[0];
if (! newtab)
error (SORT_FAILURE, 0, _("empty tab"));
if (optarg[1])
{
if (STREQ (optarg, "\\0"))
newtab = '\0';
else
{
/* Provoke with `sort -txx'. Complain about
"multi-character tab" instead of "multibyte tab", so
that the diagnostic's wording does not need to be
changed once multibyte characters are supported. */
error (SORT_FAILURE, 0, _("multi-character tab %s"),
quote (optarg));
}
}
if (tab != TAB_DEFAULT && tab != newtab)
error (SORT_FAILURE, 0, _("incompatible tabs"));
tab = newtab;
}
break;
case 'T':
add_temp_dir (optarg);
break;
case PARALLEL_OPTION:
nthreads = specify_nthreads (oi, c, optarg);
break;
case 'u':
unique = true;
break;
case 'y':
/* Accept and ignore e.g. -y0 for compatibility with Solaris 2.x
through Solaris 7. It is also accepted by many non-Solaris
"sort" implementations, e.g., AIX 5.2, HP-UX 11i v2, IRIX 6.5.
-y is marked as obsolete starting with Solaris 8 (1999), but is
still accepted as of Solaris 10 prerelease (2004).
Solaris 2.5.1 "sort -y 100" reads the input file "100", but
emulate Solaris 8 and 9 "sort -y 100" which ignores the "100",
and which in general ignores the argument after "-y" if it
consists entirely of digits (it can even be empty). */
if (optarg == argv[optind - 1])
{
char const *p;
for (p = optarg; ISDIGIT (*p); p++)
continue;
optind -= (*p != '\0');
}
break;
case 'z':
eolchar = 0;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (SORT_FAILURE);
}
}
if (files_from)
{
FILE *stream;
/* When using --files0-from=F, you may not specify any files
on the command-line. */
if (nfiles)
{
error (0, 0, _("extra operand %s"), quote (files[0]));
fprintf (stderr, "%s\n",
_("file operands cannot be combined with --files0-from"));
usage (SORT_FAILURE);
}
if (STREQ (files_from, "-"))
stream = stdin;
else
{
stream = fopen (files_from, "r");
if (stream == NULL)
error (SORT_FAILURE, errno, _("cannot open %s for reading"),
quote (files_from));
}
readtokens0_init (&tok);
if (! readtokens0 (stream, &tok) || fclose (stream) != 0)
error (SORT_FAILURE, 0, _("cannot read file names from %s"),
quote (files_from));
if (tok.n_tok)
{
size_t i;
free (files);
files = tok.tok;
nfiles = tok.n_tok;
for (i = 0; i < nfiles; i++)
{
if (STREQ (files[i], "-"))
error (SORT_FAILURE, 0, _("when reading file names from stdin, "
"no file name of %s allowed"),
quote (files[i]));
else if (files[i][0] == '\0')
{
/* Using the standard `filename:line-number:' prefix here is
not totally appropriate, since NUL is the separator, not NL,
but it might be better than nothing. */
unsigned long int file_number = i + 1;
error (SORT_FAILURE, 0,
_("%s:%lu: invalid zero-length file name"),
quotearg_colon (files_from), file_number);
}
}
}
else
error (SORT_FAILURE, 0, _("no input from %s"),
quote (files_from));
}
/* Inheritance of global options to individual keys. */
for (key = keylist; key; key = key->next)
{
if (default_key_compare (key) && !key->reverse)
{
key->ignore = gkey.ignore;
key->translate = gkey.translate;
key->skipsblanks = gkey.skipsblanks;
key->skipeblanks = gkey.skipeblanks;
key->month = gkey.month;
key->numeric = gkey.numeric;
key->general_numeric = gkey.general_numeric;
key->human_numeric = gkey.human_numeric;
key->version = gkey.version;
key->random = gkey.random;
key->reverse = gkey.reverse;
}
need_random |= key->random;
}
if (!keylist && !default_key_compare (&gkey))
{
gkey_only = true;
insertkey (&gkey);
need_random |= gkey.random;
}
check_ordering_compatibility ();
/* Disable this combination so that users are less likely
to inadvertantly update a file with debugging enabled.
Also it simplifies the code for handling temp files. */
if (debug && outfile)
error (SORT_FAILURE, 0, _("options -o and --debug are incompatible"));
if (debug)
{
/* Always output the locale in debug mode, since this
is such a common source of confusion. */
if (hard_LC_COLLATE)
error (0, 0, _("using %s sorting rules"),
quote (setlocale (LC_COLLATE, NULL)));
else
error (0, 0, _("using simple byte comparison"));
key_warnings (&gkey, gkey_only);
}
reverse = gkey.reverse;
if (need_random)
{
/* Threading does not lock the randread_source structure, so
downgrade to one thread to avoid race conditions. */
nthreads = 1;
randread_source = randread_new (random_source, MD5_DIGEST_SIZE);
if (! randread_source)
die (_("open failed"), random_source);
}
if (temp_dir_count == 0)
{
char const *tmp_dir = getenv ("TMPDIR");
add_temp_dir (tmp_dir ? tmp_dir : DEFAULT_TMPDIR);
}
if (nfiles == 0)
{
static char *minus = (char *) "-";
nfiles = 1;
free (files);
files = −
}
/* Need to re-check that we meet the minimum requirement for memory
usage with the final value for NMERGE. */
if (0 < sort_size)
sort_size = MAX (sort_size, MIN_SORT_SIZE);
if (checkonly)
{
if (nfiles > 1)
error (SORT_FAILURE, 0, _("extra operand %s not allowed with -%c"),
quote (files[1]), checkonly);
if (outfile)
{
static char opts[] = {0, 'o', 0};
opts[0] = checkonly;
incompatible_options (opts);
}
/* POSIX requires that sort return 1 IFF invoked with -c or -C and the
input is not properly sorted. */
exit (check (files[0], checkonly) ? EXIT_SUCCESS : SORT_OUT_OF_ORDER);
}
if (mergeonly)
{
struct sortfile *sortfiles = xcalloc (nfiles, sizeof *sortfiles);
size_t i;
for (i = 0; i < nfiles; ++i)
sortfiles[i].name = files[i];
merge (sortfiles, 0, nfiles, outfile);
IF_LINT (free (sortfiles));
}
else
{
/* If NTHREADS > number of cores on the machine, spinlocking
could be wasteful. */
unsigned long int np2 = num_processors (NPROC_CURRENT_OVERRIDABLE);
if (!nthreads || nthreads > np2)
nthreads = np2;
sort (files, nfiles, outfile, nthreads);
}
if (have_read_stdin && fclose (stdin) == EOF)
die (_("close failed"), "-");
exit (EXIT_SUCCESS);
}
|