1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
|
/* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
Copyright (C) 1985, 1988, 1990-1991, 1995-2012 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/>. */
/* If ls_mode is LS_MULTI_COL,
the multi-column format is the default regardless
of the type of output device.
This is for the 'dir' program.
If ls_mode is LS_LONG_FORMAT,
the long format is the default regardless of the
type of output device.
This is for the 'vdir' program.
If ls_mode is LS_LS,
the output format depends on whether the output
device is a terminal.
This is for the 'ls' program. */
/* Written by Richard Stallman and David MacKenzie. */
/* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
Flaherty <dennisf@denix.elk.miles.com> based on original patches by
Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
#include <config.h>
#include <sys/types.h>
#include <termios.h>
#if HAVE_STROPTS_H
# include <stropts.h>
#endif
#include <sys/ioctl.h>
#ifdef WINSIZE_IN_PTEM
# include <sys/stream.h>
# include <sys/ptem.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <setjmp.h>
#include <pwd.h>
#include <getopt.h>
#include <signal.h>
#include <selinux/selinux.h>
#include <wchar.h>
#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
# define sigprocmask(How, Set, Oset) /* empty */
# define sigset_t int
# if ! HAVE_SIGINTERRUPT
# define siginterrupt(sig, flag) /* empty */
# endif
#endif
/* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
restart syscalls after a signal handler fires. This may cause
colors to get messed up on the screen if 'ls' is interrupted, but
that's the best we can do on such a platform. */
#ifndef SA_RESTART
# define SA_RESTART 0
#endif
#include "system.h"
#include <fnmatch.h>
#include "acl.h"
#include "argmatch.h"
#include "dev-ino.h"
#include "error.h"
#include "filenamecat.h"
#include "hard-locale.h"
#include "hash.h"
#include "human.h"
#include "filemode.h"
#include "filevercmp.h"
#include "idcache.h"
#include "ls.h"
#include "mbswidth.h"
#include "mpsort.h"
#include "obstack.h"
#include "quote.h"
#include "quotearg.h"
#include "stat-size.h"
#include "stat-time.h"
#include "strftime.h"
#include "xstrtol.h"
#include "areadlink.h"
#include "mbsalign.h"
/* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
include guards with some premature versions of libcap.
For more details, see <http://bugzilla.redhat.com/483548>. */
#ifdef HAVE_CAP
# include <sys/capability.h>
#endif
#define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
: (ls_mode == LS_MULTI_COL \
? "dir" : "vdir"))
#define AUTHORS \
proper_name ("Richard M. Stallman"), \
proper_name ("David MacKenzie")
#define obstack_chunk_alloc malloc
#define obstack_chunk_free free
/* Return an int indicating the result of comparing two integers.
Subtracting doesn't always work, due to overflow. */
#define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
/* Unix-based readdir implementations have historically returned a dirent.d_ino
value that is sometimes not equal to the stat-obtained st_ino value for
that same entry. This error occurs for a readdir entry that refers
to a mount point. readdir's error is to return the inode number of
the underlying directory -- one that typically cannot be stat'ed, as
long as a file system is mounted on that directory. RELIABLE_D_INO
encapsulates whether we can use the more efficient approach of relying
on readdir-supplied d_ino values, or whether we must incur the cost of
calling stat or lstat to obtain each guaranteed-valid inode number. */
#ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
# define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
#endif
#if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
# define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
#else
# define RELIABLE_D_INO(dp) D_INO (dp)
#endif
#if ! HAVE_STRUCT_STAT_ST_AUTHOR
# define st_author st_uid
#endif
enum filetype
{
unknown,
fifo,
chardev,
directory,
blockdev,
normal,
symbolic_link,
sock,
whiteout,
arg_directory
};
/* Display letters and indicators for each filetype.
Keep these in sync with enum filetype. */
static char const filetype_letter[] = "?pcdb-lswd";
/* Ensure that filetype and filetype_letter have the same
number of elements. */
verify (sizeof filetype_letter - 1 == arg_directory + 1);
#define FILETYPE_INDICATORS \
{ \
C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
C_LINK, C_SOCK, C_FILE, C_DIR \
}
enum acl_type
{
ACL_T_NONE,
ACL_T_SELINUX_ONLY,
ACL_T_YES
};
struct fileinfo
{
/* The file name. */
char *name;
/* For symbolic link, name of the file linked to, otherwise zero. */
char *linkname;
struct stat stat;
enum filetype filetype;
/* For symbolic link and long listing, st_mode of file linked to, otherwise
zero. */
mode_t linkmode;
/* SELinux security context. */
security_context_t scontext;
bool stat_ok;
/* For symbolic link and color printing, true if linked-to file
exists, otherwise false. */
bool linkok;
/* For long listings, true if the file has an access control list,
or an SELinux security context. */
enum acl_type acl_type;
/* For color listings, true if a regular file has capability info. */
bool has_capability;
};
#define LEN_STR_PAIR(s) sizeof (s) - 1, s
/* Null is a valid character in a color indicator (think about Epson
printers, for example) so we have to use a length/buffer string
type. */
struct bin_str
{
size_t len; /* Number of bytes */
const char *string; /* Pointer to the same */
};
#if ! HAVE_TCGETPGRP
# define tcgetpgrp(Fd) 0
#endif
static size_t quote_name (FILE *out, const char *name,
struct quoting_options const *options,
size_t *width);
static char *make_link_name (char const *name, char const *linkname);
static int decode_switches (int argc, char **argv);
static bool file_ignored (char const *name);
static uintmax_t gobble_file (char const *name, enum filetype type,
ino_t inode, bool command_line_arg,
char const *dirname);
static bool print_color_indicator (const struct fileinfo *f,
bool symlink_target);
static void put_indicator (const struct bin_str *ind);
static void add_ignore_pattern (const char *pattern);
static void attach (char *dest, const char *dirname, const char *name);
static void clear_files (void);
static void extract_dirs_from_files (char const *dirname,
bool command_line_arg);
static void get_link_name (char const *filename, struct fileinfo *f,
bool command_line_arg);
static void indent (size_t from, size_t to);
static size_t calculate_columns (bool by_columns);
static void print_current_files (void);
static void print_dir (char const *name, char const *realname,
bool command_line_arg);
static size_t print_file_name_and_frills (const struct fileinfo *f,
size_t start_col);
static void print_horizontal (void);
static int format_user_width (uid_t u);
static int format_group_width (gid_t g);
static void print_long_format (const struct fileinfo *f);
static void print_many_per_line (void);
static size_t print_name_with_quoting (const struct fileinfo *f,
bool symlink_target,
struct obstack *stack,
size_t start_col);
static void prep_non_filename_text (void);
static bool print_type_indicator (bool stat_ok, mode_t mode,
enum filetype type);
static void print_with_commas (void);
static void queue_directory (char const *name, char const *realname,
bool command_line_arg);
static void sort_files (void);
static void parse_ls_color (void);
/* Initial size of hash table.
Most hierarchies are likely to be shallower than this. */
#define INITIAL_TABLE_SIZE 30
/* The set of 'active' directories, from the current command-line argument
to the level in the hierarchy at which files are being listed.
A directory is represented by its device and inode numbers (struct dev_ino).
A directory is added to this set when ls begins listing it or its
entries, and it is removed from the set just after ls has finished
processing it. This set is used solely to detect loops, e.g., with
mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
static Hash_table *active_dir_set;
#define LOOP_DETECT (!!active_dir_set)
/* The table of files in the current directory:
'cwd_file' points to a vector of `struct fileinfo', one per file.
'cwd_n_alloc' is the number of elements space has been allocated for.
'cwd_n_used' is the number actually in use. */
/* Address of block containing the files that are described. */
static struct fileinfo *cwd_file;
/* Length of block that 'cwd_file' points to, measured in files. */
static size_t cwd_n_alloc;
/* Index of first unused slot in 'cwd_file'. */
static size_t cwd_n_used;
/* Vector of pointers to files, in proper sorted order, and the number
of entries allocated for it. */
static void **sorted_file;
static size_t sorted_file_alloc;
/* When true, in a color listing, color each symlink name according to the
type of file it points to. Otherwise, color them according to the 'ln'
directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
regardless. This is set when 'ln=target' appears in LS_COLORS. */
static bool color_symlink_as_referent;
/* mode of appropriate file for colorization */
#define FILE_OR_LINK_MODE(File) \
((color_symlink_as_referent && (File)->linkok) \
? (File)->linkmode : (File)->stat.st_mode)
/* Record of one pending directory waiting to be listed. */
struct pending
{
char *name;
/* If the directory is actually the file pointed to by a symbolic link we
were told to list, 'realname' will contain the name of the symbolic
link, otherwise zero. */
char *realname;
bool command_line_arg;
struct pending *next;
};
static struct pending *pending_dirs;
/* Current time in seconds and nanoseconds since 1970, updated as
needed when deciding whether a file is recent. */
static struct timespec current_time;
static bool print_scontext;
static char UNKNOWN_SECURITY_CONTEXT[] = "?";
/* Whether any of the files has an ACL. This affects the width of the
mode column. */
static bool any_has_acl;
/* The number of columns to use for columns containing inode numbers,
block sizes, link counts, owners, groups, authors, major device
numbers, minor device numbers, and file sizes, respectively. */
static int inode_number_width;
static int block_size_width;
static int nlink_width;
static int scontext_width;
static int owner_width;
static int group_width;
static int author_width;
static int major_device_number_width;
static int minor_device_number_width;
static int file_size_width;
/* Option flags */
/* long_format for lots of info, one per line.
one_per_line for just names, one per line.
many_per_line for just names, many per line, sorted vertically.
horizontal for just names, many per line, sorted horizontally.
with_commas for just names, many per line, separated by commas.
-l (and other options that imply -l), -1, -C, -x and -m control
this parameter. */
enum format
{
long_format, /* -l and other options that imply -l */
one_per_line, /* -1 */
many_per_line, /* -C */
horizontal, /* -x */
with_commas /* -m */
};
static enum format format;
/* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
ISO-style time stamps, though shorter than 'full-iso'. 'iso' uses shorter
ISO-style time stamps. 'locale' uses locale-dependent time stamps. */
enum time_style
{
full_iso_time_style, /* --time-style=full-iso */
long_iso_time_style, /* --time-style=long-iso */
iso_time_style, /* --time-style=iso */
locale_time_style /* --time-style=locale */
};
static char const *const time_style_args[] =
{
"full-iso", "long-iso", "iso", "locale", NULL
};
static enum time_style const time_style_types[] =
{
full_iso_time_style, long_iso_time_style, iso_time_style,
locale_time_style
};
ARGMATCH_VERIFY (time_style_args, time_style_types);
/* Type of time to print or sort by. Controlled by -c and -u.
The values of each item of this enum are important since they are
used as indices in the sort functions array (see sort_files()). */
enum time_type
{
time_mtime, /* default */
time_ctime, /* -c */
time_atime, /* -u */
time_numtypes /* the number of elements of this enum */
};
static enum time_type time_type;
/* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
The values of each item of this enum are important since they are
used as indices in the sort functions array (see sort_files()). */
enum sort_type
{
sort_none = -1, /* -U */
sort_name, /* default */
sort_extension, /* -X */
sort_size, /* -S */
sort_version, /* -v */
sort_time, /* -t */
sort_numtypes /* the number of elements of this enum */
};
static enum sort_type sort_type;
/* Direction of sort.
false means highest first if numeric,
lowest first if alphabetic;
these are the defaults.
true means the opposite order in each case. -r */
static bool sort_reverse;
/* True means to display owner information. -g turns this off. */
static bool print_owner = true;
/* True means to display author information. */
static bool print_author;
/* True means to display group information. -G and -o turn this off. */
static bool print_group = true;
/* True means print the user and group id's as numbers rather
than as names. -n */
static bool numeric_ids;
/* True means mention the size in blocks of each file. -s */
static bool print_block_size;
/* Human-readable options for output, when printing block counts. */
static int human_output_opts;
/* The units to use when printing block counts. */
static uintmax_t output_block_size;
/* Likewise, but for file sizes. */
static int file_human_output_opts;
static uintmax_t file_output_block_size = 1;
/* Follow the output with a special string. Using this format,
Emacs' dired mode starts up twice as fast, and can handle all
strange characters in file names. */
static bool dired;
/* 'none' means don't mention the type of files.
'slash' means mention directories only, with a '/'.
'file_type' means mention file types.
'classify' means mention file types and mark executables.
Controlled by -F, -p, and --indicator-style. */
enum indicator_style
{
none, /* --indicator-style=none */
slash, /* -p, --indicator-style=slash */
file_type, /* --indicator-style=file-type */
classify /* -F, --indicator-style=classify */
};
static enum indicator_style indicator_style;
/* Names of indicator styles. */
static char const *const indicator_style_args[] =
{
"none", "slash", "file-type", "classify", NULL
};
static enum indicator_style const indicator_style_types[] =
{
none, slash, file_type, classify
};
ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
/* True means use colors to mark types. Also define the different
colors as well as the stuff for the LS_COLORS environment variable.
The LS_COLORS variable is now in a termcap-like format. */
static bool print_with_color;
/* Whether we used any colors in the output so far. If so, we will
need to restore the default color later. If not, we will need to
call prep_non_filename_text before using color for the first time. */
static bool used_color = false;
enum color_type
{
color_never, /* 0: default or --color=never */
color_always, /* 1: --color=always */
color_if_tty /* 2: --color=tty */
};
enum Dereference_symlink
{
DEREF_UNDEFINED = 1,
DEREF_NEVER,
DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
DEREF_ALWAYS /* -L */
};
enum indicator_no
{
C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
C_FIFO, C_SOCK,
C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
C_CLR_TO_EOL
};
static const char *const indicator_name[]=
{
"lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
"bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
"ow", "tw", "ca", "mh", "cl", NULL
};
struct color_ext_type
{
struct bin_str ext; /* The extension we're looking for */
struct bin_str seq; /* The sequence to output when we do */
struct color_ext_type *next; /* Next in list */
};
static struct bin_str color_indicator[] =
{
{ LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
{ LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
{ 0, NULL }, /* ec: End color (replaces lc+no+rc) */
{ LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
{ 0, NULL }, /* no: Normal */
{ 0, NULL }, /* fi: File: default */
{ LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
{ LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
{ LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
{ LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
{ LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
{ LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
{ 0, NULL }, /* mi: Missing file: undefined */
{ 0, NULL }, /* or: Orphaned symlink: undefined */
{ LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
{ LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
{ LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
{ LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
{ LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
{ LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
{ LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
{ LEN_STR_PAIR ("30;41") }, /* ca: black on red */
{ 0, NULL }, /* mh: disabled by default */
{ LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
};
/* FIXME: comment */
static struct color_ext_type *color_ext_list = NULL;
/* Buffer for color sequences */
static char *color_buf;
/* True means to check for orphaned symbolic link, for displaying
colors. */
static bool check_symlink_color;
/* True means mention the inode number of each file. -i */
static bool print_inode;
/* What to do with symbolic links. Affected by -d, -F, -H, -l (and
other options that imply -l), and -L. */
static enum Dereference_symlink dereference;
/* True means when a directory is found, display info on its
contents. -R */
static bool recursive;
/* True means when an argument is a directory name, display info
on it itself. -d */
static bool immediate_dirs;
/* True means that directories are grouped before files. */
static bool directories_first;
/* Which files to ignore. */
static enum
{
/* Ignore files whose names start with '.', and files specified by
--hide and --ignore. */
IGNORE_DEFAULT,
/* Ignore '.', '..', and files specified by --ignore. */
IGNORE_DOT_AND_DOTDOT,
/* Ignore only files specified by --ignore. */
IGNORE_MINIMAL
} ignore_mode;
/* A linked list of shell-style globbing patterns. If a non-argument
file name matches any of these patterns, it is ignored.
Controlled by -I. Multiple -I options accumulate.
The -B option adds '*~' and '.*~' to this list. */
struct ignore_pattern
{
const char *pattern;
struct ignore_pattern *next;
};
static struct ignore_pattern *ignore_patterns;
/* Similar to IGNORE_PATTERNS, except that -a or -A causes this
variable itself to be ignored. */
static struct ignore_pattern *hide_patterns;
/* True means output nongraphic chars in file names as '?'.
(-q, --hide-control-chars)
qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
independent. The algorithm is: first, obey the quoting style to get a
string representing the file name; then, if qmark_funny_chars is set,
replace all nonprintable chars in that string with '?'. It's necessary
to replace nonprintable chars even in quoted strings, because we don't
want to mess up the terminal if control chars get sent to it, and some
quoting methods pass through control chars as-is. */
static bool qmark_funny_chars;
/* Quoting options for file and dir name output. */
static struct quoting_options *filename_quoting_options;
static struct quoting_options *dirname_quoting_options;
/* The number of chars per hardware tab stop. Setting this to zero
inhibits the use of TAB characters for separating columns. -T */
static size_t tabsize;
/* True means print each directory name before listing it. */
static bool print_dir_name;
/* The line length to use for breaking lines in many-per-line format.
Can be set with -w. */
static size_t line_length;
/* If true, the file listing format requires that stat be called on
each file. */
static bool format_needs_stat;
/* Similar to 'format_needs_stat', but set if only the file type is
needed. */
static bool format_needs_type;
/* An arbitrary limit on the number of bytes in a printed time stamp.
This is set to a relatively small value to avoid the need to worry
about denial-of-service attacks on servers that run "ls" on behalf
of remote clients. 1000 bytes should be enough for any practical
time stamp format. */
enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
/* strftime formats for non-recent and recent files, respectively, in
-l output. */
static char const *long_time_format[2] =
{
/* strftime format for non-recent files (older than 6 months), in
-l output. This should contain the year, month and day (at
least), in an order that is understood by people in your
locale's territory. Please try to keep the number of used
screen columns small, because many people work in windows with
only 80 columns. But make this as wide as the other string
below, for recent files. */
/* TRANSLATORS: ls output needs to be aligned for ease of reading,
so be wary of using variable width fields from the locale.
Note %b is handled specially by ls and aligned correctly.
Note also that specifying a width as in %5b is erroneous as strftime
will count bytes rather than characters in multibyte locales. */
N_("%b %e %Y"),
/* strftime format for recent files (younger than 6 months), in -l
output. This should contain the month, day and time (at
least), in an order that is understood by people in your
locale's territory. Please try to keep the number of used
screen columns small, because many people work in windows with
only 80 columns. But make this as wide as the other string
above, for non-recent files. */
/* TRANSLATORS: ls output needs to be aligned for ease of reading,
so be wary of using variable width fields from the locale.
Note %b is handled specially by ls and aligned correctly.
Note also that specifying a width as in %5b is erroneous as strftime
will count bytes rather than characters in multibyte locales. */
N_("%b %e %H:%M")
};
/* The set of signals that are caught. */
static sigset_t caught_signals;
/* If nonzero, the value of the pending fatal signal. */
static sig_atomic_t volatile interrupt_signal;
/* A count of the number of pending stop signals that have been received. */
static sig_atomic_t volatile stop_signal_count;
/* Desired exit status. */
static int exit_status;
/* Exit statuses. */
enum
{
/* "ls" had a minor problem. E.g., while processing a directory,
ls obtained the name of an entry via readdir, yet was later
unable to stat that name. This happens when listing a directory
in which entries are actively being removed or renamed. */
LS_MINOR_PROBLEM = 1,
/* "ls" had more serious trouble (e.g., memory exhausted, invalid
option or failure to stat a command line argument. */
LS_FAILURE = 2
};
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
AUTHOR_OPTION = CHAR_MAX + 1,
BLOCK_SIZE_OPTION,
COLOR_OPTION,
DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
FILE_TYPE_INDICATOR_OPTION,
FORMAT_OPTION,
FULL_TIME_OPTION,
GROUP_DIRECTORIES_FIRST_OPTION,
HIDE_OPTION,
INDICATOR_STYLE_OPTION,
QUOTING_STYLE_OPTION,
SHOW_CONTROL_CHARS_OPTION,
SI_OPTION,
SORT_OPTION,
TIME_OPTION,
TIME_STYLE_OPTION
};
static struct option const long_options[] =
{
{"all", no_argument, NULL, 'a'},
{"escape", no_argument, NULL, 'b'},
{"directory", no_argument, NULL, 'd'},
{"dired", no_argument, NULL, 'D'},
{"full-time", no_argument, NULL, FULL_TIME_OPTION},
{"group-directories-first", no_argument, NULL,
GROUP_DIRECTORIES_FIRST_OPTION},
{"human-readable", no_argument, NULL, 'h'},
{"inode", no_argument, NULL, 'i'},
{"kibibytes", no_argument, NULL, 'k'},
{"numeric-uid-gid", no_argument, NULL, 'n'},
{"no-group", no_argument, NULL, 'G'},
{"hide-control-chars", no_argument, NULL, 'q'},
{"reverse", no_argument, NULL, 'r'},
{"size", no_argument, NULL, 's'},
{"width", required_argument, NULL, 'w'},
{"almost-all", no_argument, NULL, 'A'},
{"ignore-backups", no_argument, NULL, 'B'},
{"classify", no_argument, NULL, 'F'},
{"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
{"si", no_argument, NULL, SI_OPTION},
{"dereference-command-line", no_argument, NULL, 'H'},
{"dereference-command-line-symlink-to-dir", no_argument, NULL,
DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
{"hide", required_argument, NULL, HIDE_OPTION},
{"ignore", required_argument, NULL, 'I'},
{"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
{"dereference", no_argument, NULL, 'L'},
{"literal", no_argument, NULL, 'N'},
{"quote-name", no_argument, NULL, 'Q'},
{"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
{"recursive", no_argument, NULL, 'R'},
{"format", required_argument, NULL, FORMAT_OPTION},
{"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
{"sort", required_argument, NULL, SORT_OPTION},
{"tabsize", required_argument, NULL, 'T'},
{"time", required_argument, NULL, TIME_OPTION},
{"time-style", required_argument, NULL, TIME_STYLE_OPTION},
{"color", optional_argument, NULL, COLOR_OPTION},
{"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
{"context", no_argument, 0, 'Z'},
{"author", no_argument, NULL, AUTHOR_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
static char const *const format_args[] =
{
"verbose", "long", "commas", "horizontal", "across",
"vertical", "single-column", NULL
};
static enum format const format_types[] =
{
long_format, long_format, with_commas, horizontal, horizontal,
many_per_line, one_per_line
};
ARGMATCH_VERIFY (format_args, format_types);
static char const *const sort_args[] =
{
"none", "time", "size", "extension", "version", NULL
};
static enum sort_type const sort_types[] =
{
sort_none, sort_time, sort_size, sort_extension, sort_version
};
ARGMATCH_VERIFY (sort_args, sort_types);
static char const *const time_args[] =
{
"atime", "access", "use", "ctime", "status", NULL
};
static enum time_type const time_types[] =
{
time_atime, time_atime, time_atime, time_ctime, time_ctime
};
ARGMATCH_VERIFY (time_args, time_types);
static char const *const color_args[] =
{
/* force and none are for compatibility with another color-ls version */
"always", "yes", "force",
"never", "no", "none",
"auto", "tty", "if-tty", NULL
};
static enum color_type const color_types[] =
{
color_always, color_always, color_always,
color_never, color_never, color_never,
color_if_tty, color_if_tty, color_if_tty
};
ARGMATCH_VERIFY (color_args, color_types);
/* Information about filling a column. */
struct column_info
{
bool valid_len;
size_t line_len;
size_t *col_arr;
};
/* Array with information about column filledness. */
static struct column_info *column_info;
/* Maximum number of columns ever possible for this display. */
static size_t max_idx;
/* The minimum width of a column is 3: 1 character for the name and 2
for the separating white space. */
#define MIN_COLUMN_WIDTH 3
/* This zero-based index is used solely with the --dired option.
When that option is in effect, this counter is incremented for each
byte of output generated by this program so that the beginning
and ending indices (in that output) of every file name can be recorded
and later output themselves. */
static size_t dired_pos;
#define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
/* Write S to STREAM and increment DIRED_POS by S_LEN. */
#define DIRED_FPUTS(s, stream, s_len) \
do {fputs (s, stream); dired_pos += s_len;} while (0)
/* Like DIRED_FPUTS, but for use when S is a literal string. */
#define DIRED_FPUTS_LITERAL(s, stream) \
do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
#define DIRED_INDENT() \
do \
{ \
if (dired) \
DIRED_FPUTS_LITERAL (" ", stdout); \
} \
while (0)
/* With --dired, store pairs of beginning and ending indices of filenames. */
static struct obstack dired_obstack;
/* With --dired, store pairs of beginning and ending indices of any
directory names that appear as headers (just before 'total' line)
for lists of directory entries. Such directory names are seen when
listing hierarchies using -R and when a directory is listed with at
least one other command line argument. */
static struct obstack subdired_obstack;
/* Save the current index on the specified obstack, OBS. */
#define PUSH_CURRENT_DIRED_POS(obs) \
do \
{ \
if (dired) \
obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
} \
while (0)
/* With -R, this stack is used to help detect directory cycles.
The device/inode pairs on this stack mirror the pairs in the
active_dir_set hash table. */
static struct obstack dev_ino_obstack;
/* Push a pair onto the device/inode stack. */
#define DEV_INO_PUSH(Dev, Ino) \
do \
{ \
struct dev_ino *di; \
obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
di->st_dev = (Dev); \
di->st_ino = (Ino); \
} \
while (0)
/* Pop a dev/ino struct off the global dev_ino_obstack
and return that struct. */
static struct dev_ino
dev_ino_pop (void)
{
assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
}
/* Note the use commented out below:
#define ASSERT_MATCHING_DEV_INO(Name, Di) \
do \
{ \
struct stat sb; \
assert (Name); \
assert (0 <= stat (Name, &sb)); \
assert (sb.st_dev == Di.st_dev); \
assert (sb.st_ino == Di.st_ino); \
} \
while (0)
*/
/* Write to standard output PREFIX, followed by the quoting style and
a space-separated list of the integers stored in OS all on one line. */
static void
dired_dump_obstack (const char *prefix, struct obstack *os)
{
size_t n_pos;
n_pos = obstack_object_size (os) / sizeof (dired_pos);
if (n_pos > 0)
{
size_t i;
size_t *pos;
pos = (size_t *) obstack_finish (os);
fputs (prefix, stdout);
for (i = 0; i < n_pos; i++)
printf (" %lu", (unsigned long int) pos[i]);
putchar ('\n');
}
}
/* Read the abbreviated month names from the locale, to align them
and to determine the max width of the field and to truncate names
greater than our max allowed.
Note even though this handles multibyte locales correctly
it's not restricted to them as single byte locales can have
variable width abbreviated months and also precomputing/caching
the names was seen to increase the performance of ls significantly. */
/* max number of display cells to use */
enum { MAX_MON_WIDTH = 5 };
/* In the unlikely event that the abmon[] storage is not big enough
an error message will be displayed, and we revert to using
unmodified abbreviated month names from the locale database. */
static char abmon[12][MAX_MON_WIDTH * 2 * MB_LEN_MAX + 1];
/* minimum width needed to align %b, 0 => don't use precomputed values. */
static size_t required_mon_width;
static size_t
abmon_init (void)
{
#ifdef HAVE_NL_LANGINFO
required_mon_width = MAX_MON_WIDTH;
size_t curr_max_width;
do
{
curr_max_width = required_mon_width;
required_mon_width = 0;
for (int i = 0; i < 12; i++)
{
size_t width = curr_max_width;
size_t req = mbsalign (nl_langinfo (ABMON_1 + i),
abmon[i], sizeof (abmon[i]),
&width, MBS_ALIGN_LEFT, 0);
if (req == (size_t) -1 || req >= sizeof (abmon[i]))
{
required_mon_width = 0; /* ignore precomputed strings. */
return required_mon_width;
}
required_mon_width = MAX (required_mon_width, width);
}
}
while (curr_max_width > required_mon_width);
#endif
return required_mon_width;
}
static size_t
dev_ino_hash (void const *x, size_t table_size)
{
struct dev_ino const *p = x;
return (uintmax_t) p->st_ino % table_size;
}
static bool
dev_ino_compare (void const *x, void const *y)
{
struct dev_ino const *a = x;
struct dev_ino const *b = y;
return SAME_INODE (*a, *b) ? true : false;
}
static void
dev_ino_free (void *x)
{
free (x);
}
/* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
active directories. Return true if there is already a matching
entry in the table. */
static bool
visit_dir (dev_t dev, ino_t ino)
{
struct dev_ino *ent;
struct dev_ino *ent_from_table;
bool found_match;
ent = xmalloc (sizeof *ent);
ent->st_ino = ino;
ent->st_dev = dev;
/* Attempt to insert this entry into the table. */
ent_from_table = hash_insert (active_dir_set, ent);
if (ent_from_table == NULL)
{
/* Insertion failed due to lack of memory. */
xalloc_die ();
}
found_match = (ent_from_table != ent);
if (found_match)
{
/* ent was not inserted, so free it. */
free (ent);
}
return found_match;
}
static void
free_pending_ent (struct pending *p)
{
free (p->name);
free (p->realname);
free (p);
}
static bool
is_colored (enum indicator_no type)
{
size_t len = color_indicator[type].len;
char const *s = color_indicator[type].string;
return ! (len == 0
|| (len == 1 && STRNCMP_LIT (s, "0") == 0)
|| (len == 2 && STRNCMP_LIT (s, "00") == 0));
}
static void
restore_default_color (void)
{
put_indicator (&color_indicator[C_LEFT]);
put_indicator (&color_indicator[C_RIGHT]);
}
static void
set_normal_color (void)
{
if (print_with_color && is_colored (C_NORM))
{
put_indicator (&color_indicator[C_LEFT]);
put_indicator (&color_indicator[C_NORM]);
put_indicator (&color_indicator[C_RIGHT]);
}
}
/* An ordinary signal was received; arrange for the program to exit. */
static void
sighandler (int sig)
{
if (! SA_NOCLDSTOP)
signal (sig, SIG_IGN);
if (! interrupt_signal)
interrupt_signal = sig;
}
/* A SIGTSTP was received; arrange for the program to suspend itself. */
static void
stophandler (int sig)
{
if (! SA_NOCLDSTOP)
signal (sig, stophandler);
if (! interrupt_signal)
stop_signal_count++;
}
/* Process any pending signals. If signals are caught, this function
should be called periodically. Ideally there should never be an
unbounded amount of time when signals are not being processed.
Signal handling can restore the default colors, so callers must
immediately change colors after invoking this function. */
static void
process_signals (void)
{
while (interrupt_signal || stop_signal_count)
{
int sig;
int stops;
sigset_t oldset;
if (used_color)
restore_default_color ();
fflush (stdout);
sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
/* Reload interrupt_signal and stop_signal_count, in case a new
signal was handled before sigprocmask took effect. */
sig = interrupt_signal;
stops = stop_signal_count;
/* SIGTSTP is special, since the application can receive that signal
more than once. In this case, don't set the signal handler to the
default. Instead, just raise the uncatchable SIGSTOP. */
if (stops)
{
stop_signal_count = stops - 1;
sig = SIGSTOP;
}
else
signal (sig, SIG_DFL);
/* Exit or suspend the program. */
raise (sig);
sigprocmask (SIG_SETMASK, &oldset, NULL);
/* If execution reaches here, then the program has been
continued (after being suspended). */
}
}
int
main (int argc, char **argv)
{
int i;
struct pending *thispend;
int n_files;
/* The signals that are trapped, and the number of such signals. */
static int const sig[] =
{
/* This one is handled specially. */
SIGTSTP,
/* 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
bool caught_sig[nsigs];
#endif
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
initialize_exit_failure (LS_FAILURE);
atexit (close_stdout);
assert (ARRAY_CARDINALITY (color_indicator) + 1
== ARRAY_CARDINALITY (indicator_name));
exit_status = EXIT_SUCCESS;
print_dir_name = true;
pending_dirs = NULL;
current_time.tv_sec = TYPE_MINIMUM (time_t);
current_time.tv_nsec = -1;
i = decode_switches (argc, argv);
if (print_with_color)
parse_ls_color ();
/* Test print_with_color again, because the call to parse_ls_color
may have just reset it -- e.g., if LS_COLORS is invalid. */
if (print_with_color)
{
/* Avoid following symbolic links when possible. */
if (is_colored (C_ORPHAN)
|| (is_colored (C_EXEC) && color_symlink_as_referent)
|| (is_colored (C_MISSING) && format == long_format))
check_symlink_color = true;
/* If the standard output is a controlling terminal, watch out
for signals, so that the colors can be restored to the
default state if "ls" is suspended or interrupted. */
if (0 <= tcgetpgrp (STDOUT_FILENO))
{
int j;
#if SA_NOCLDSTOP
struct sigaction act;
sigemptyset (&caught_signals);
for (j = 0; j < nsigs; j++)
{
sigaction (sig[j], NULL, &act);
if (act.sa_handler != SIG_IGN)
sigaddset (&caught_signals, sig[j]);
}
act.sa_mask = caught_signals;
act.sa_flags = SA_RESTART;
for (j = 0; j < nsigs; j++)
if (sigismember (&caught_signals, sig[j]))
{
act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
sigaction (sig[j], &act, NULL);
}
#else
for (j = 0; j < nsigs; j++)
{
caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
if (caught_sig[j])
{
signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
siginterrupt (sig[j], 0);
}
}
#endif
}
}
if (dereference == DEREF_UNDEFINED)
dereference = ((immediate_dirs
|| indicator_style == classify
|| format == long_format)
? DEREF_NEVER
: DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
/* When using -R, initialize a data structure we'll use to
detect any directory cycles. */
if (recursive)
{
active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
dev_ino_hash,
dev_ino_compare,
dev_ino_free);
if (active_dir_set == NULL)
xalloc_die ();
obstack_init (&dev_ino_obstack);
}
format_needs_stat = sort_type == sort_time || sort_type == sort_size
|| format == long_format
|| print_scontext
|| print_block_size;
format_needs_type = (! format_needs_stat
&& (recursive
|| print_with_color
|| indicator_style != none
|| directories_first));
if (dired)
{
obstack_init (&dired_obstack);
obstack_init (&subdired_obstack);
}
cwd_n_alloc = 100;
cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
cwd_n_used = 0;
clear_files ();
n_files = argc - i;
if (n_files <= 0)
{
if (immediate_dirs)
gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
else
queue_directory (".", NULL, true);
}
else
do
gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
while (i < argc);
if (cwd_n_used)
{
sort_files ();
if (!immediate_dirs)
extract_dirs_from_files (NULL, true);
/* 'cwd_n_used' might be zero now. */
}
/* In the following if/else blocks, it is sufficient to test 'pending_dirs'
(and not pending_dirs->name) because there may be no markers in the queue
at this point. A marker may be enqueued when extract_dirs_from_files is
called with a non-empty string or via print_dir. */
if (cwd_n_used)
{
print_current_files ();
if (pending_dirs)
DIRED_PUTCHAR ('\n');
}
else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
print_dir_name = false;
while (pending_dirs)
{
thispend = pending_dirs;
pending_dirs = pending_dirs->next;
if (LOOP_DETECT)
{
if (thispend->name == NULL)
{
/* thispend->name == NULL means this is a marker entry
indicating we've finished processing the directory.
Use its dev/ino numbers to remove the corresponding
entry from the active_dir_set hash table. */
struct dev_ino di = dev_ino_pop ();
struct dev_ino *found = hash_delete (active_dir_set, &di);
/* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
assert (found);
dev_ino_free (found);
free_pending_ent (thispend);
continue;
}
}
print_dir (thispend->name, thispend->realname,
thispend->command_line_arg);
free_pending_ent (thispend);
print_dir_name = true;
}
if (print_with_color)
{
int j;
if (used_color)
{
/* Skip the restore when it would be a no-op, i.e.,
when left is "\033[" and right is "m". */
if (!(color_indicator[C_LEFT].len == 2
&& memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
&& color_indicator[C_RIGHT].len == 1
&& color_indicator[C_RIGHT].string[0] == 'm'))
restore_default_color ();
}
fflush (stdout);
/* Restore the default signal handling. */
#if SA_NOCLDSTOP
for (j = 0; j < nsigs; j++)
if (sigismember (&caught_signals, sig[j]))
signal (sig[j], SIG_DFL);
#else
for (j = 0; j < nsigs; j++)
if (caught_sig[j])
signal (sig[j], SIG_DFL);
#endif
/* Act on any signals that arrived before the default was restored.
This can process signals out of order, but there doesn't seem to
be an easy way to do them in order, and the order isn't that
important anyway. */
for (j = stop_signal_count; j; j--)
raise (SIGSTOP);
j = interrupt_signal;
if (j)
raise (j);
}
if (dired)
{
/* No need to free these since we're about to exit. */
dired_dump_obstack ("//DIRED//", &dired_obstack);
dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
quoting_style_args[get_quoting_style (filename_quoting_options)]);
}
if (LOOP_DETECT)
{
assert (hash_get_n_entries (active_dir_set) == 0);
hash_free (active_dir_set);
}
exit (exit_status);
}
/* Set all the option flags according to the switches specified.
Return the index of the first non-option argument. */
static int
decode_switches (int argc, char **argv)
{
char *time_style_option = NULL;
bool sort_type_specified = false;
bool kibibytes_specified = false;
qmark_funny_chars = false;
/* initialize all switches to default settings */
switch (ls_mode)
{
case LS_MULTI_COL:
/* This is for the 'dir' program. */
format = many_per_line;
set_quoting_style (NULL, escape_quoting_style);
break;
case LS_LONG_FORMAT:
/* This is for the 'vdir' program. */
format = long_format;
set_quoting_style (NULL, escape_quoting_style);
break;
case LS_LS:
/* This is for the 'ls' program. */
if (isatty (STDOUT_FILENO))
{
format = many_per_line;
/* See description of qmark_funny_chars, above. */
qmark_funny_chars = true;
}
else
{
format = one_per_line;
qmark_funny_chars = false;
}
break;
default:
abort ();
}
time_type = time_mtime;
sort_type = sort_name;
sort_reverse = false;
numeric_ids = false;
print_block_size = false;
indicator_style = none;
print_inode = false;
dereference = DEREF_UNDEFINED;
recursive = false;
immediate_dirs = false;
ignore_mode = IGNORE_DEFAULT;
ignore_patterns = NULL;
hide_patterns = NULL;
print_scontext = false;
/* FIXME: put this in a function. */
{
char const *q_style = getenv ("QUOTING_STYLE");
if (q_style)
{
int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
if (0 <= i)
set_quoting_style (NULL, quoting_style_vals[i]);
else
error (0, 0,
_("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
quotearg (q_style));
}
}
line_length = 80;
{
char const *p = getenv ("COLUMNS");
if (p && *p)
{
unsigned long int tmp_ulong;
if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
&& 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
{
line_length = tmp_ulong;
}
else
{
error (0, 0,
_("ignoring invalid width in environment variable COLUMNS: %s"),
quotearg (p));
}
}
}
#ifdef TIOCGWINSZ
{
struct winsize ws;
if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
&& 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
line_length = ws.ws_col;
}
#endif
{
char const *p = getenv ("TABSIZE");
tabsize = 8;
if (p)
{
unsigned long int tmp_ulong;
if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
&& tmp_ulong <= SIZE_MAX)
{
tabsize = tmp_ulong;
}
else
{
error (0, 0,
_("ignoring invalid tab size in environment variable TABSIZE: %s"),
quotearg (p));
}
}
}
while (true)
{
int oi = -1;
int c = getopt_long (argc, argv,
"abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
long_options, &oi);
if (c == -1)
break;
switch (c)
{
case 'a':
ignore_mode = IGNORE_MINIMAL;
break;
case 'b':
set_quoting_style (NULL, escape_quoting_style);
break;
case 'c':
time_type = time_ctime;
break;
case 'd':
immediate_dirs = true;
break;
case 'f':
/* Same as enabling -a -U and disabling -l -s. */
ignore_mode = IGNORE_MINIMAL;
sort_type = sort_none;
sort_type_specified = true;
/* disable -l */
if (format == long_format)
format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
print_block_size = false; /* disable -s */
print_with_color = false; /* disable --color */
break;
case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
indicator_style = file_type;
break;
case 'g':
format = long_format;
print_owner = false;
break;
case 'h':
file_human_output_opts = human_output_opts =
human_autoscale | human_SI | human_base_1024;
file_output_block_size = output_block_size = 1;
break;
case 'i':
print_inode = true;
break;
case 'k':
kibibytes_specified = true;
break;
case 'l':
format = long_format;
break;
case 'm':
format = with_commas;
break;
case 'n':
numeric_ids = true;
format = long_format;
break;
case 'o': /* Just like -l, but don't display group info. */
format = long_format;
print_group = false;
break;
case 'p':
indicator_style = slash;
break;
case 'q':
qmark_funny_chars = true;
break;
case 'r':
sort_reverse = true;
break;
case 's':
print_block_size = true;
break;
case 't':
sort_type = sort_time;
sort_type_specified = true;
break;
case 'u':
time_type = time_atime;
break;
case 'v':
sort_type = sort_version;
sort_type_specified = true;
break;
case 'w':
{
unsigned long int tmp_ulong;
if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
|| ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
error (LS_FAILURE, 0, _("invalid line width: %s"),
quotearg (optarg));
line_length = tmp_ulong;
break;
}
case 'x':
format = horizontal;
break;
case 'A':
if (ignore_mode == IGNORE_DEFAULT)
ignore_mode = IGNORE_DOT_AND_DOTDOT;
break;
case 'B':
add_ignore_pattern ("*~");
add_ignore_pattern (".*~");
break;
case 'C':
format = many_per_line;
break;
case 'D':
dired = true;
break;
case 'F':
indicator_style = classify;
break;
case 'G': /* inhibit display of group info */
print_group = false;
break;
case 'H':
dereference = DEREF_COMMAND_LINE_ARGUMENTS;
break;
case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
break;
case 'I':
add_ignore_pattern (optarg);
break;
case 'L':
dereference = DEREF_ALWAYS;
break;
case 'N':
set_quoting_style (NULL, literal_quoting_style);
break;
case 'Q':
set_quoting_style (NULL, c_quoting_style);
break;
case 'R':
recursive = true;
break;
case 'S':
sort_type = sort_size;
sort_type_specified = true;
break;
case 'T':
{
unsigned long int tmp_ulong;
if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
|| SIZE_MAX < tmp_ulong)
error (LS_FAILURE, 0, _("invalid tab size: %s"),
quotearg (optarg));
tabsize = tmp_ulong;
break;
}
case 'U':
sort_type = sort_none;
sort_type_specified = true;
break;
case 'X':
sort_type = sort_extension;
sort_type_specified = true;
break;
case '1':
/* -1 has no effect after -l. */
if (format != long_format)
format = one_per_line;
break;
case AUTHOR_OPTION:
print_author = true;
break;
case HIDE_OPTION:
{
struct ignore_pattern *hide = xmalloc (sizeof *hide);
hide->pattern = optarg;
hide->next = hide_patterns;
hide_patterns = hide;
}
break;
case SORT_OPTION:
sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
sort_type_specified = true;
break;
case GROUP_DIRECTORIES_FIRST_OPTION:
directories_first = true;
break;
case TIME_OPTION:
time_type = XARGMATCH ("--time", optarg, time_args, time_types);
break;
case FORMAT_OPTION:
format = XARGMATCH ("--format", optarg, format_args, format_types);
break;
case FULL_TIME_OPTION:
format = long_format;
time_style_option = bad_cast ("full-iso");
break;
case COLOR_OPTION:
{
int i;
if (optarg)
i = XARGMATCH ("--color", optarg, color_args, color_types);
else
/* Using --color with no argument is equivalent to using
--color=always. */
i = color_always;
print_with_color = (i == color_always
|| (i == color_if_tty
&& isatty (STDOUT_FILENO)));
if (print_with_color)
{
/* Don't use TAB characters in output. Some terminal
emulators can't handle the combination of tabs and
color codes on the same line. */
tabsize = 0;
}
break;
}
case INDICATOR_STYLE_OPTION:
indicator_style = XARGMATCH ("--indicator-style", optarg,
indicator_style_args,
indicator_style_types);
break;
case QUOTING_STYLE_OPTION:
set_quoting_style (NULL,
XARGMATCH ("--quoting-style", optarg,
quoting_style_args,
quoting_style_vals));
break;
case TIME_STYLE_OPTION:
time_style_option = optarg;
break;
case SHOW_CONTROL_CHARS_OPTION:
qmark_funny_chars = false;
break;
case BLOCK_SIZE_OPTION:
{
enum strtol_error e = human_options (optarg, &human_output_opts,
&output_block_size);
if (e != LONGINT_OK)
xstrtol_fatal (e, oi, 0, long_options, optarg);
file_human_output_opts = human_output_opts;
file_output_block_size = output_block_size;
}
break;
case SI_OPTION:
file_human_output_opts = human_output_opts =
human_autoscale | human_SI;
file_output_block_size = output_block_size = 1;
break;
case 'Z':
print_scontext = true;
break;
case_GETOPT_HELP_CHAR;
case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (LS_FAILURE);
}
}
if (! output_block_size)
{
char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
human_options (ls_block_size,
&human_output_opts, &output_block_size);
if (ls_block_size || getenv ("BLOCK_SIZE"))
{
file_human_output_opts = human_output_opts;
file_output_block_size = output_block_size;
}
if (kibibytes_specified)
{
human_output_opts = 0;
output_block_size = 1024;
}
}
max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
filename_quoting_options = clone_quoting_options (NULL);
if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
set_char_quoting (filename_quoting_options, ' ', 1);
if (file_type <= indicator_style)
{
char const *p;
for (p = "*=>@|" + indicator_style - file_type; *p; p++)
set_char_quoting (filename_quoting_options, *p, 1);
}
dirname_quoting_options = clone_quoting_options (NULL);
set_char_quoting (dirname_quoting_options, ':', 1);
/* --dired is meaningful only with --format=long (-l).
Otherwise, ignore it. FIXME: warn about this?
Alternatively, make --dired imply --format=long? */
if (dired && format != long_format)
dired = false;
/* If -c or -u is specified and not -l (or any other option that implies -l),
and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
The behavior of ls when using either -c or -u but with neither -l nor -t
appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
sort by atime (this is the one that's not specified by the POSIX spec),
-lu means show atime and sort by name, -lut means show atime and sort
by atime. */
if ((time_type == time_ctime || time_type == time_atime)
&& !sort_type_specified && format != long_format)
{
sort_type = sort_time;
}
if (format == long_format)
{
char *style = time_style_option;
static char const posix_prefix[] = "posix-";
if (! style)
if (! (style = getenv ("TIME_STYLE")))
style = bad_cast ("locale");
while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
{
if (! hard_locale (LC_TIME))
return optind;
style += sizeof posix_prefix - 1;
}
if (*style == '+')
{
char *p0 = style + 1;
char *p1 = strchr (p0, '\n');
if (! p1)
p1 = p0;
else
{
if (strchr (p1 + 1, '\n'))
error (LS_FAILURE, 0, _("invalid time style format %s"),
quote (p0));
*p1++ = '\0';
}
long_time_format[0] = p0;
long_time_format[1] = p1;
}
else
{
ptrdiff_t res = argmatch (style, time_style_args,
(char const *) time_style_types,
sizeof (*time_style_types));
if (res < 0)
{
/* This whole block used to be a simple use of XARGMATCH.
but that didn't print the "posix-"-prefixed variants or
the "+"-prefixed format string option upon failure. */
argmatch_invalid ("time style", style, res);
/* The following is a manual expansion of argmatch_valid,
but with the added "+ ..." description and the [posix-]
prefixes prepended. Note that this simplification works
only because all four existing time_style_types values
are distinct. */
fputs (_("Valid arguments are:\n"), stderr);
char const *const *p = time_style_args;
while (*p)
fprintf (stderr, " - [posix-]%s\n", *p++);
fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
" format\n"), stderr);
usage (LS_FAILURE);
}
switch (res)
{
case full_iso_time_style:
long_time_format[0] = long_time_format[1] =
"%Y-%m-%d %H:%M:%S.%N %z";
break;
case long_iso_time_style:
long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
break;
case iso_time_style:
long_time_format[0] = "%Y-%m-%d ";
long_time_format[1] = "%m-%d %H:%M";
break;
case locale_time_style:
if (hard_locale (LC_TIME))
{
int i;
for (i = 0; i < 2; i++)
long_time_format[i] =
dcgettext (NULL, long_time_format[i], LC_TIME);
}
}
}
/* Note we leave %5b etc. alone so user widths/flags are honored. */
if (strstr (long_time_format[0], "%b")
|| strstr (long_time_format[1], "%b"))
if (!abmon_init ())
error (0, 0, _("error initializing month strings"));
}
return optind;
}
/* Parse a string as part of the LS_COLORS variable; this may involve
decoding all kinds of escape characters. If equals_end is set an
unescaped equal sign ends the string, otherwise only a : or \0
does. Set *OUTPUT_COUNT to the number of bytes output. Return
true if successful.
The resulting string is *not* null-terminated, but may contain
embedded nulls.
Note that both dest and src are char **; on return they point to
the first free byte after the array and the character that ended
the input string, respectively. */
static bool
get_funky_string (char **dest, const char **src, bool equals_end,
size_t *output_count)
{
char num; /* For numerical codes */
size_t count; /* Something to count with */
enum {
ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
} state;
const char *p;
char *q;
p = *src; /* We don't want to double-indirect */
q = *dest; /* the whole darn time. */
count = 0; /* No characters counted in yet. */
num = 0;
state = ST_GND; /* Start in ground state. */
while (state < ST_END)
{
switch (state)
{
case ST_GND: /* Ground state (no escapes) */
switch (*p)
{
case ':':
case '\0':
state = ST_END; /* End of string */
break;
case '\\':
state = ST_BACKSLASH; /* Backslash scape sequence */
++p;
break;
case '^':
state = ST_CARET; /* Caret escape */
++p;
break;
case '=':
if (equals_end)
{
state = ST_END; /* End */
break;
}
/* else fall through */
default:
*(q++) = *(p++);
++count;
break;
}
break;
case ST_BACKSLASH: /* Backslash escaped character */
switch (*p)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
state = ST_OCTAL; /* Octal sequence */
num = *p - '0';
break;
case 'x':
case 'X':
state = ST_HEX; /* Hex sequence */
num = 0;
break;
case 'a': /* Bell */
num = '\a';
break;
case 'b': /* Backspace */
num = '\b';
break;
case 'e': /* Escape */
num = 27;
break;
case 'f': /* Form feed */
num = '\f';
break;
case 'n': /* Newline */
num = '\n';
break;
case 'r': /* Carriage return */
num = '\r';
break;
case 't': /* Tab */
num = '\t';
break;
case 'v': /* Vtab */
num = '\v';
break;
case '?': /* Delete */
num = 127;
break;
case '_': /* Space */
num = ' ';
break;
case '\0': /* End of string */
state = ST_ERROR; /* Error! */
break;
default: /* Escaped character like \ ^ : = */
num = *p;
break;
}
if (state == ST_BACKSLASH)
{
*(q++) = num;
++count;
state = ST_GND;
}
++p;
break;
case ST_OCTAL: /* Octal sequence */
if (*p < '0' || *p > '7')
{
*(q++) = num;
++count;
state = ST_GND;
}
else
num = (num << 3) + (*(p++) - '0');
break;
case ST_HEX: /* Hex sequence */
switch (*p)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
num = (num << 4) + (*(p++) - '0');
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
num = (num << 4) + (*(p++) - 'a') + 10;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
num = (num << 4) + (*(p++) - 'A') + 10;
break;
default:
*(q++) = num;
++count;
state = ST_GND;
break;
}
break;
case ST_CARET: /* Caret escape */
state = ST_GND; /* Should be the next state... */
if (*p >= '@' && *p <= '~')
{
*(q++) = *(p++) & 037;
++count;
}
else if (*p == '?')
{
*(q++) = 127;
++count;
}
else
state = ST_ERROR;
break;
default:
abort ();
}
}
*dest = q;
*src = p;
*output_count = count;
return state != ST_ERROR;
}
enum parse_state
{
PS_START = 1,
PS_2,
PS_3,
PS_4,
PS_DONE,
PS_FAIL
};
static void
parse_ls_color (void)
{
const char *p; /* Pointer to character being parsed */
char *buf; /* color_buf buffer pointer */
int ind_no; /* Indicator number */
char label[3]; /* Indicator label */
struct color_ext_type *ext; /* Extension we are working on */
if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
return;
ext = NULL;
strcpy (label, "??");
/* This is an overly conservative estimate, but any possible
LS_COLORS string will *not* generate a color_buf longer than
itself, so it is a safe way of allocating a buffer in
advance. */
buf = color_buf = xstrdup (p);
enum parse_state state = PS_START;
while (true)
{
switch (state)
{
case PS_START: /* First label character */
switch (*p)
{
case ':':
++p;
break;
case '*':
/* Allocate new extension block and add to head of
linked list (this way a later definition will
override an earlier one, which can be useful for
having terminal-specific defs override global). */
ext = xmalloc (sizeof *ext);
ext->next = color_ext_list;
color_ext_list = ext;
++p;
ext->ext.string = buf;
state = (get_funky_string (&buf, &p, true, &ext->ext.len)
? PS_4 : PS_FAIL);
break;
case '\0':
state = PS_DONE; /* Done! */
goto done;
default: /* Assume it is file type label */
label[0] = *(p++);
state = PS_2;
break;
}
break;
case PS_2: /* Second label character */
if (*p)
{
label[1] = *(p++);
state = PS_3;
}
else
state = PS_FAIL; /* Error */
break;
case PS_3: /* Equal sign after indicator label */
state = PS_FAIL; /* Assume failure... */
if (*(p++) == '=')/* It *should* be... */
{
for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
{
if (STREQ (label, indicator_name[ind_no]))
{
color_indicator[ind_no].string = buf;
state = (get_funky_string (&buf, &p, false,
&color_indicator[ind_no].len)
? PS_START : PS_FAIL);
break;
}
}
if (state == PS_FAIL)
error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
}
break;
case PS_4: /* Equal sign after *.ext */
if (*(p++) == '=')
{
ext->seq.string = buf;
state = (get_funky_string (&buf, &p, false, &ext->seq.len)
? PS_START : PS_FAIL);
}
else
state = PS_FAIL;
break;
case PS_FAIL:
goto done;
default:
abort ();
}
}
done:
if (state == PS_FAIL)
{
struct color_ext_type *e;
struct color_ext_type *e2;
error (0, 0,
_("unparsable value for LS_COLORS environment variable"));
free (color_buf);
for (e = color_ext_list; e != NULL; /* empty */)
{
e2 = e;
e = e->next;
free (e2);
}
print_with_color = false;
}
if (color_indicator[C_LINK].len == 6
&& !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
color_symlink_as_referent = true;
}
/* Set the exit status to report a failure. If SERIOUS, it is a
serious failure; otherwise, it is merely a minor problem. */
static void
set_exit_status (bool serious)
{
if (serious)
exit_status = LS_FAILURE;
else if (exit_status == EXIT_SUCCESS)
exit_status = LS_MINOR_PROBLEM;
}
/* Assuming a failure is serious if SERIOUS, use the printf-style
MESSAGE to report the failure to access a file named FILE. Assume
errno is set appropriately for the failure. */
static void
file_failure (bool serious, char const *message, char const *file)
{
error (0, errno, message, quotearg_colon (file));
set_exit_status (serious);
}
/* Request that the directory named NAME have its contents listed later.
If REALNAME is nonzero, it will be used instead of NAME when the
directory name is printed. This allows symbolic links to directories
to be treated as regular directories but still be listed under their
real names. NAME == NULL is used to insert a marker entry for the
directory named in REALNAME.
If NAME is non-NULL, we use its dev/ino information to save
a call to stat -- when doing a recursive (-R) traversal.
COMMAND_LINE_ARG means this directory was mentioned on the command line. */
static void
queue_directory (char const *name, char const *realname, bool command_line_arg)
{
struct pending *new = xmalloc (sizeof *new);
new->realname = realname ? xstrdup (realname) : NULL;
new->name = name ? xstrdup (name) : NULL;
new->command_line_arg = command_line_arg;
new->next = pending_dirs;
pending_dirs = new;
}
/* Read directory NAME, and list the files in it.
If REALNAME is nonzero, print its name instead of NAME;
this is used for symbolic links to directories.
COMMAND_LINE_ARG means this directory was mentioned on the command line. */
static void
print_dir (char const *name, char const *realname, bool command_line_arg)
{
DIR *dirp;
struct dirent *next;
uintmax_t total_blocks = 0;
static bool first = true;
errno = 0;
dirp = opendir (name);
if (!dirp)
{
file_failure (command_line_arg, _("cannot open directory %s"), name);
return;
}
if (LOOP_DETECT)
{
struct stat dir_stat;
int fd = dirfd (dirp);
/* If dirfd failed, endure the overhead of using stat. */
if ((0 <= fd
? fstat (fd, &dir_stat)
: stat (name, &dir_stat)) < 0)
{
file_failure (command_line_arg,
_("cannot determine device and inode of %s"), name);
closedir (dirp);
return;
}
/* If we've already visited this dev/inode pair, warn that
we've found a loop, and do not process this directory. */
if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
{
error (0, 0, _("%s: not listing already-listed directory"),
quotearg_colon (name));
closedir (dirp);
set_exit_status (true);
return;
}
DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
}
if (recursive || print_dir_name)
{
if (!first)
DIRED_PUTCHAR ('\n');
first = false;
DIRED_INDENT ();
PUSH_CURRENT_DIRED_POS (&subdired_obstack);
dired_pos += quote_name (stdout, realname ? realname : name,
dirname_quoting_options, NULL);
PUSH_CURRENT_DIRED_POS (&subdired_obstack);
DIRED_FPUTS_LITERAL (":\n", stdout);
}
/* Read the directory entries, and insert the subfiles into the 'cwd_file'
table. */
clear_files ();
while (1)
{
/* Set errno to zero so we can distinguish between a readdir failure
and when readdir simply finds that there are no more entries. */
errno = 0;
next = readdir (dirp);
if (next)
{
if (! file_ignored (next->d_name))
{
enum filetype type = unknown;
#if HAVE_STRUCT_DIRENT_D_TYPE
switch (next->d_type)
{
case DT_BLK: type = blockdev; break;
case DT_CHR: type = chardev; break;
case DT_DIR: type = directory; break;
case DT_FIFO: type = fifo; break;
case DT_LNK: type = symbolic_link; break;
case DT_REG: type = normal; break;
case DT_SOCK: type = sock; break;
# ifdef DT_WHT
case DT_WHT: type = whiteout; break;
# endif
}
#endif
total_blocks += gobble_file (next->d_name, type,
RELIABLE_D_INO (next),
false, name);
/* In this narrow case, print out each name right away, so
ls uses constant memory while processing the entries of
this directory. Useful when there are many (millions)
of entries in a directory. */
if (format == one_per_line && sort_type == sort_none
&& !print_block_size && !recursive)
{
/* We must call sort_files in spite of
"sort_type == sort_none" for its initialization
of the sorted_file vector. */
sort_files ();
print_current_files ();
clear_files ();
}
}
}
else if (errno != 0)
{
file_failure (command_line_arg, _("reading directory %s"), name);
if (errno != EOVERFLOW)
break;
}
else
break;
/* When processing a very large directory, and since we've inhibited
interrupts, this loop would take so long that ls would be annoyingly
uninterruptible. This ensures that it handles signals promptly. */
process_signals ();
}
if (closedir (dirp) != 0)
{
file_failure (command_line_arg, _("closing directory %s"), name);
/* Don't return; print whatever we got. */
}
/* Sort the directory contents. */
sort_files ();
/* If any member files are subdirectories, perhaps they should have their
contents listed rather than being mentioned here as files. */
if (recursive)
extract_dirs_from_files (name, command_line_arg);
if (format == long_format || print_block_size)
{
const char *p;
char buf[LONGEST_HUMAN_READABLE + 1];
DIRED_INDENT ();
p = _("total");
DIRED_FPUTS (p, stdout, strlen (p));
DIRED_PUTCHAR (' ');
p = human_readable (total_blocks, buf, human_output_opts,
ST_NBLOCKSIZE, output_block_size);
DIRED_FPUTS (p, stdout, strlen (p));
DIRED_PUTCHAR ('\n');
}
if (cwd_n_used)
print_current_files ();
}
/* Add 'pattern' to the list of patterns for which files that match are
not listed. */
static void
add_ignore_pattern (const char *pattern)
{
struct ignore_pattern *ignore;
ignore = xmalloc (sizeof *ignore);
ignore->pattern = pattern;
/* Add it to the head of the linked list. */
ignore->next = ignore_patterns;
ignore_patterns = ignore;
}
/* Return true if one of the PATTERNS matches FILE. */
static bool
patterns_match (struct ignore_pattern const *patterns, char const *file)
{
struct ignore_pattern const *p;
for (p = patterns; p; p = p->next)
if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
return true;
return false;
}
/* Return true if FILE should be ignored. */
static bool
file_ignored (char const *name)
{
return ((ignore_mode != IGNORE_MINIMAL
&& name[0] == '.'
&& (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
|| (ignore_mode == IGNORE_DEFAULT
&& patterns_match (hide_patterns, name))
|| patterns_match (ignore_patterns, name));
}
/* POSIX requires that a file size be printed without a sign, even
when negative. Assume the typical case where negative sizes are
actually positive values that have wrapped around. */
static uintmax_t
unsigned_file_size (off_t size)
{
return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
}
#ifdef HAVE_CAP
/* Return true if NAME has a capability (see linux/capability.h) */
static bool
has_capability (char const *name)
{
char *result;
bool has_cap;
cap_t cap_d = cap_get_file (name);
if (cap_d == NULL)
return false;
result = cap_to_text (cap_d, NULL);
cap_free (cap_d);
if (!result)
return false;
/* check if human-readable capability string is empty */
has_cap = !!*result;
cap_free (result);
return has_cap;
}
#else
static bool
has_capability (char const *name ATTRIBUTE_UNUSED)
{
return false;
}
#endif
/* Enter and remove entries in the table 'cwd_file'. */
static void
free_ent (struct fileinfo *f)
{
free (f->name);
free (f->linkname);
if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
freecon (f->scontext);
}
/* Empty the table of files. */
static void
clear_files (void)
{
size_t i;
for (i = 0; i < cwd_n_used; i++)
{
struct fileinfo *f = sorted_file[i];
free_ent (f);
}
cwd_n_used = 0;
any_has_acl = false;
inode_number_width = 0;
block_size_width = 0;
nlink_width = 0;
owner_width = 0;
group_width = 0;
author_width = 0;
scontext_width = 0;
major_device_number_width = 0;
minor_device_number_width = 0;
file_size_width = 0;
}
/* Add a file to the current table of files.
Verify that the file exists, and print an error message if it does not.
Return the number of blocks that the file occupies. */
static uintmax_t
gobble_file (char const *name, enum filetype type, ino_t inode,
bool command_line_arg, char const *dirname)
{
uintmax_t blocks = 0;
struct fileinfo *f;
/* An inode value prior to gobble_file necessarily came from readdir,
which is not used for command line arguments. */
assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
if (cwd_n_used == cwd_n_alloc)
{
cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
cwd_n_alloc *= 2;
}
f = &cwd_file[cwd_n_used];
memset (f, '\0', sizeof *f);
f->stat.st_ino = inode;
f->filetype = type;
if (command_line_arg
|| format_needs_stat
/* When coloring a directory (we may know the type from
direct.d_type), we have to stat it in order to indicate
sticky and/or other-writable attributes. */
|| (type == directory && print_with_color
&& (is_colored (C_OTHER_WRITABLE)
|| is_colored (C_STICKY)
|| is_colored (C_STICKY_OTHER_WRITABLE)))
/* When dereferencing symlinks, the inode and type must come from
stat, but readdir provides the inode and type of lstat. */
|| ((print_inode || format_needs_type)
&& (type == symbolic_link || type == unknown)
&& (dereference == DEREF_ALWAYS
|| (command_line_arg && dereference != DEREF_NEVER)
|| color_symlink_as_referent || check_symlink_color))
/* Command line dereferences are already taken care of by the above
assertion that the inode number is not yet known. */
|| (print_inode && inode == NOT_AN_INODE_NUMBER)
|| (format_needs_type
&& (type == unknown || command_line_arg
/* --indicator-style=classify (aka -F)
requires that we stat each regular file
to see if it's executable. */
|| (type == normal && (indicator_style == classify
/* This is so that --color ends up
highlighting files with these mode
bits set even when options like -F are
not specified. Note we do a redundant
stat in the very unlikely case where
C_CAP is set but not the others. */
|| (print_with_color
&& (is_colored (C_EXEC)
|| is_colored (C_SETUID)
|| is_colored (C_SETGID)
|| is_colored (C_CAP)))
)))))
{
/* Absolute name of this file. */
char *absolute_name;
bool do_deref;
int err;
if (name[0] == '/' || dirname[0] == 0)
absolute_name = (char *) name;
else
{
absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
attach (absolute_name, dirname, name);
}
switch (dereference)
{
case DEREF_ALWAYS:
err = stat (absolute_name, &f->stat);
do_deref = true;
break;
case DEREF_COMMAND_LINE_ARGUMENTS:
case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
if (command_line_arg)
{
bool need_lstat;
err = stat (absolute_name, &f->stat);
do_deref = true;
if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
break;
need_lstat = (err < 0
? errno == ENOENT
: ! S_ISDIR (f->stat.st_mode));
if (!need_lstat)
break;
/* stat failed because of ENOENT, maybe indicating a dangling
symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
directory, and --dereference-command-line-symlink-to-dir is
in effect. Fall through so that we call lstat instead. */
}
default: /* DEREF_NEVER */
err = lstat (absolute_name, &f->stat);
do_deref = false;
break;
}
if (err != 0)
{
/* Failure to stat a command line argument leads to
an exit status of 2. For other files, stat failure
provokes an exit status of 1. */
file_failure (command_line_arg,
_("cannot access %s"), absolute_name);
if (command_line_arg)
return 0;
f->name = xstrdup (name);
cwd_n_used++;
return 0;
}
f->stat_ok = true;
/* Note has_capability() adds around 30% runtime to `ls --color` */
if ((type == normal || S_ISREG (f->stat.st_mode))
&& print_with_color && is_colored (C_CAP))
f->has_capability = has_capability (absolute_name);
if (format == long_format || print_scontext)
{
bool have_selinux = false;
bool have_acl = false;
int attr_len = (do_deref
? getfilecon (absolute_name, &f->scontext)
: lgetfilecon (absolute_name, &f->scontext));
err = (attr_len < 0);
if (err == 0)
have_selinux = ! STREQ ("unlabeled", f->scontext);
else
{
f->scontext = UNKNOWN_SECURITY_CONTEXT;
/* When requesting security context information, don't make
ls fail just because the file (even a command line argument)
isn't on the right type of file system. I.e., a getfilecon
failure isn't in the same class as a stat failure. */
if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
err = 0;
}
if (err == 0 && format == long_format)
{
int n = file_has_acl (absolute_name, &f->stat);
err = (n < 0);
have_acl = (0 < n);
}
f->acl_type = (!have_selinux && !have_acl
? ACL_T_NONE
: (have_selinux && !have_acl
? ACL_T_SELINUX_ONLY
: ACL_T_YES));
any_has_acl |= f->acl_type != ACL_T_NONE;
if (err)
error (0, errno, "%s", quotearg_colon (absolute_name));
}
if (S_ISLNK (f->stat.st_mode)
&& (format == long_format || check_symlink_color))
{
char *linkname;
struct stat linkstats;
get_link_name (absolute_name, f, command_line_arg);
linkname = make_link_name (absolute_name, f->linkname);
/* Avoid following symbolic links when possible, ie, when
they won't be traced and when no indicator is needed. */
if (linkname
&& (file_type <= indicator_style || check_symlink_color)
&& stat (linkname, &linkstats) == 0)
{
f->linkok = true;
/* Symbolic links to directories that are mentioned on the
command line are automatically traced if not being
listed as files. */
if (!command_line_arg || format == long_format
|| !S_ISDIR (linkstats.st_mode))
{
/* Get the linked-to file's mode for the filetype indicator
in long listings. */
f->linkmode = linkstats.st_mode;
}
}
free (linkname);
}
/* When not distinguishing types of symlinks, pretend we know that
it is stat'able, so that it will be colored as a regular symlink,
and not as an orphan. */
if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
f->linkok = true;
if (S_ISLNK (f->stat.st_mode))
f->filetype = symbolic_link;
else if (S_ISDIR (f->stat.st_mode))
{
if (command_line_arg && !immediate_dirs)
f->filetype = arg_directory;
else
f->filetype = directory;
}
else
f->filetype = normal;
blocks = ST_NBLOCKS (f->stat);
if (format == long_format || print_block_size)
{
char buf[LONGEST_HUMAN_READABLE + 1];
int len = mbswidth (human_readable (blocks, buf, human_output_opts,
ST_NBLOCKSIZE, output_block_size),
0);
if (block_size_width < len)
block_size_width = len;
}
if (format == long_format)
{
if (print_owner)
{
int len = format_user_width (f->stat.st_uid);
if (owner_width < len)
owner_width = len;
}
if (print_group)
{
int len = format_group_width (f->stat.st_gid);
if (group_width < len)
group_width = len;
}
if (print_author)
{
int len = format_user_width (f->stat.st_author);
if (author_width < len)
author_width = len;
}
}
if (print_scontext)
{
int len = strlen (f->scontext);
if (scontext_width < len)
scontext_width = len;
}
if (format == long_format)
{
char b[INT_BUFSIZE_BOUND (uintmax_t)];
int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
if (nlink_width < b_len)
nlink_width = b_len;
if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
{
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
if (major_device_number_width < len)
major_device_number_width = len;
len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
if (minor_device_number_width < len)
minor_device_number_width = len;
len = major_device_number_width + 2 + minor_device_number_width;
if (file_size_width < len)
file_size_width = len;
}
else
{
char buf[LONGEST_HUMAN_READABLE + 1];
uintmax_t size = unsigned_file_size (f->stat.st_size);
int len = mbswidth (human_readable (size, buf,
file_human_output_opts,
1, file_output_block_size),
0);
if (file_size_width < len)
file_size_width = len;
}
}
}
if (print_inode)
{
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
int len = strlen (umaxtostr (f->stat.st_ino, buf));
if (inode_number_width < len)
inode_number_width = len;
}
f->name = xstrdup (name);
cwd_n_used++;
return blocks;
}
/* Return true if F refers to a directory. */
static bool
is_directory (const struct fileinfo *f)
{
return f->filetype == directory || f->filetype == arg_directory;
}
/* Put the name of the file that FILENAME is a symbolic link to
into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
FILENAME is a command-line argument. */
static void
get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
{
f->linkname = areadlink_with_size (filename, f->stat.st_size);
if (f->linkname == NULL)
file_failure (command_line_arg, _("cannot read symbolic link %s"),
filename);
}
/* If 'linkname' is a relative name and 'name' contains one or more
leading directories, return 'linkname' with those directories
prepended; otherwise, return a copy of 'linkname'.
If 'linkname' is zero, return zero. */
static char *
make_link_name (char const *name, char const *linkname)
{
char *linkbuf;
size_t bufsiz;
if (!linkname)
return NULL;
if (*linkname == '/')
return xstrdup (linkname);
/* The link is to a relative name. Prepend any leading directory
in 'name' to the link name. */
linkbuf = strrchr (name, '/');
if (linkbuf == 0)
return xstrdup (linkname);
bufsiz = linkbuf - name + 1;
linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
strncpy (linkbuf, name, bufsiz);
strcpy (linkbuf + bufsiz, linkname);
return linkbuf;
}
/* Return true if the last component of NAME is '.' or '..'
This is so we don't try to recurse on `././././. ...' */
static bool
basename_is_dot_or_dotdot (const char *name)
{
char const *base = last_component (name);
return dot_or_dotdot (base);
}
/* Remove any entries from CWD_FILE that are for directories,
and queue them to be listed as directories instead.
DIRNAME is the prefix to prepend to each dirname
to make it correct relative to ls's working dir;
if it is null, no prefix is needed and "." and ".." should not be ignored.
If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
This is desirable when processing directories recursively. */
static void
extract_dirs_from_files (char const *dirname, bool command_line_arg)
{
size_t i;
size_t j;
bool ignore_dot_and_dot_dot = (dirname != NULL);
if (dirname && LOOP_DETECT)
{
/* Insert a marker entry first. When we dequeue this marker entry,
we'll know that DIRNAME has been processed and may be removed
from the set of active directories. */
queue_directory (NULL, dirname, false);
}
/* Queue the directories last one first, because queueing reverses the
order. */
for (i = cwd_n_used; i-- != 0; )
{
struct fileinfo *f = sorted_file[i];
if (is_directory (f)
&& (! ignore_dot_and_dot_dot
|| ! basename_is_dot_or_dotdot (f->name)))
{
if (!dirname || f->name[0] == '/')
queue_directory (f->name, f->linkname, command_line_arg);
else
{
char *name = file_name_concat (dirname, f->name, NULL);
queue_directory (name, f->linkname, command_line_arg);
free (name);
}
if (f->filetype == arg_directory)
free_ent (f);
}
}
/* Now delete the directories from the table, compacting all the remaining
entries. */
for (i = 0, j = 0; i < cwd_n_used; i++)
{
struct fileinfo *f = sorted_file[i];
sorted_file[j] = f;
j += (f->filetype != arg_directory);
}
cwd_n_used = j;
}
/* Use strcoll to compare strings in this locale. If an error occurs,
report an error and longjmp to failed_strcoll. */
static jmp_buf failed_strcoll;
static int
xstrcoll (char const *a, char const *b)
{
int diff;
errno = 0;
diff = strcoll (a, b);
if (errno)
{
error (0, errno, _("cannot compare file names %s and %s"),
quote_n (0, a), quote_n (1, b));
set_exit_status (false);
longjmp (failed_strcoll, 1);
}
return diff;
}
/* Comparison routines for sorting the files. */
typedef void const *V;
typedef int (*qsortFunc)(V a, V b);
/* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
The do { ... } while(0) makes it possible to use the macro more like
a statement, without violating C89 rules: */
#define DIRFIRST_CHECK(a, b) \
do \
{ \
bool a_is_dir = is_directory ((struct fileinfo const *) a); \
bool b_is_dir = is_directory ((struct fileinfo const *) b); \
if (a_is_dir && !b_is_dir) \
return -1; /* a goes before b */ \
if (!a_is_dir && b_is_dir) \
return 1; /* b goes before a */ \
} \
while (0)
/* Define the 8 different sort function variants required for each sortkey.
KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
'[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
#define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
/* direct, non-dirfirst versions */ \
static int xstrcoll_##key_name (V a, V b) \
{ return key_cmp_func (a, b, xstrcoll); } \
static int strcmp_##key_name (V a, V b) \
{ return key_cmp_func (a, b, strcmp); } \
\
/* reverse, non-dirfirst versions */ \
static int rev_xstrcoll_##key_name (V a, V b) \
{ return key_cmp_func (b, a, xstrcoll); } \
static int rev_strcmp_##key_name (V a, V b) \
{ return key_cmp_func (b, a, strcmp); } \
\
/* direct, dirfirst versions */ \
static int xstrcoll_df_##key_name (V a, V b) \
{ DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
static int strcmp_df_##key_name (V a, V b) \
{ DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
\
/* reverse, dirfirst versions */ \
static int rev_xstrcoll_df_##key_name (V a, V b) \
{ DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
static int rev_strcmp_df_##key_name (V a, V b) \
{ DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
static inline int
cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
int diff = timespec_cmp (get_stat_ctime (&b->stat),
get_stat_ctime (&a->stat));
return diff ? diff : cmp (a->name, b->name);
}
static inline int
cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
int diff = timespec_cmp (get_stat_mtime (&b->stat),
get_stat_mtime (&a->stat));
return diff ? diff : cmp (a->name, b->name);
}
static inline int
cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
int diff = timespec_cmp (get_stat_atime (&b->stat),
get_stat_atime (&a->stat));
return diff ? diff : cmp (a->name, b->name);
}
static inline int
cmp_size (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
int diff = longdiff (b->stat.st_size, a->stat.st_size);
return diff ? diff : cmp (a->name, b->name);
}
static inline int
cmp_name (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
return cmp (a->name, b->name);
}
/* Compare file extensions. Files with no extension are 'smallest'.
If extensions are the same, compare by filenames instead. */
static inline int
cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
int (*cmp) (char const *, char const *))
{
char const *base1 = strrchr (a->name, '.');
char const *base2 = strrchr (b->name, '.');
int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
return diff ? diff : cmp (a->name, b->name);
}
DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
DEFINE_SORT_FUNCTIONS (size, cmp_size)
DEFINE_SORT_FUNCTIONS (name, cmp_name)
DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
/* Compare file versions.
Unlike all other compare functions above, cmp_version depends only
on filevercmp, which does not fail (even for locale reasons), and does not
need a secondary sort key. See lib/filevercmp.h for function description.
All the other sort options, in fact, need xstrcoll and strcmp variants,
because they all use a string comparison (either as the primary or secondary
sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
locale reasons. Lastly, filevercmp is ALWAYS available with gnulib. */
static inline int
cmp_version (struct fileinfo const *a, struct fileinfo const *b)
{
return filevercmp (a->name, b->name);
}
static int xstrcoll_version (V a, V b)
{ return cmp_version (a, b); }
static int rev_xstrcoll_version (V a, V b)
{ return cmp_version (b, a); }
static int xstrcoll_df_version (V a, V b)
{ DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
static int rev_xstrcoll_df_version (V a, V b)
{ DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
/* We have 2^3 different variants for each sortkey function
(for 3 independent sort modes).
The function pointers stored in this array must be dereferenced as:
sort_variants[sort_key][use_strcmp][reverse][dirs_first]
Note that the order in which sortkeys are listed in the function pointer
array below is defined by the order of the elements in the time_type and
sort_type enums! */
#define LIST_SORTFUNCTION_VARIANTS(key_name) \
{ \
{ \
{ xstrcoll_##key_name, xstrcoll_df_##key_name }, \
{ rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
}, \
{ \
{ strcmp_##key_name, strcmp_df_##key_name }, \
{ rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
} \
}
static qsortFunc const sort_functions[][2][2][2] =
{
LIST_SORTFUNCTION_VARIANTS (name),
LIST_SORTFUNCTION_VARIANTS (extension),
LIST_SORTFUNCTION_VARIANTS (size),
{
{
{ xstrcoll_version, xstrcoll_df_version },
{ rev_xstrcoll_version, rev_xstrcoll_df_version },
},
/* We use NULL for the strcmp variants of version comparison
since as explained in cmp_version definition, version comparison
does not rely on xstrcoll, so it will never longjmp, and never
need to try the strcmp fallback. */
{
{ NULL, NULL },
{ NULL, NULL },
}
},
/* last are time sort functions */
LIST_SORTFUNCTION_VARIANTS (mtime),
LIST_SORTFUNCTION_VARIANTS (ctime),
LIST_SORTFUNCTION_VARIANTS (atime)
};
/* The number of sortkeys is calculated as
the number of elements in the sort_type enum (i.e. sort_numtypes) +
the number of elements in the time_type enum (i.e. time_numtypes) - 1
This is because when sort_type==sort_time, we have up to
time_numtypes possible sortkeys.
This line verifies at compile-time that the array of sort functions has been
initialized for all possible sortkeys. */
verify (ARRAY_CARDINALITY (sort_functions)
== sort_numtypes + time_numtypes - 1 );
/* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
static void
initialize_ordering_vector (void)
{
size_t i;
for (i = 0; i < cwd_n_used; i++)
sorted_file[i] = &cwd_file[i];
}
/* Sort the files now in the table. */
static void
sort_files (void)
{
bool use_strcmp;
if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
{
free (sorted_file);
sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
sorted_file_alloc = 3 * cwd_n_used;
}
initialize_ordering_vector ();
if (sort_type == sort_none)
return;
/* Try strcoll. If it fails, fall back on strcmp. We can't safely
ignore strcoll failures, as a failing strcoll might be a
comparison function that is not a total order, and if we ignored
the failure this might cause qsort to dump core. */
if (! setjmp (failed_strcoll))
use_strcmp = false; /* strcoll() succeeded */
else
{
use_strcmp = true;
assert (sort_type != sort_version);
initialize_ordering_vector ();
}
/* When sort_type == sort_time, use time_type as subindex. */
mpsort ((void const **) sorted_file, cwd_n_used,
sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
[use_strcmp][sort_reverse]
[directories_first]);
}
/* List all the files now in the table. */
static void
print_current_files (void)
{
size_t i;
switch (format)
{
case one_per_line:
for (i = 0; i < cwd_n_used; i++)
{
print_file_name_and_frills (sorted_file[i], 0);
putchar ('\n');
}
break;
case many_per_line:
print_many_per_line ();
break;
case horizontal:
print_horizontal ();
break;
case with_commas:
print_with_commas ();
break;
case long_format:
for (i = 0; i < cwd_n_used; i++)
{
set_normal_color ();
print_long_format (sorted_file[i]);
DIRED_PUTCHAR ('\n');
}
break;
}
}
/* Replace the first %b with precomputed aligned month names.
Note on glibc-2.7 at least, this speeds up the whole `ls -lU`
process by around 17%, compared to letting strftime() handle the %b. */
static size_t
align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm,
int __utc, int __ns)
{
const char *nfmt = fmt;
/* In the unlikely event that rpl_fmt below is not large enough,
the replacement is not done. A malloc here slows ls down by 2% */
char rpl_fmt[sizeof (abmon[0]) + 100];
const char *pb;
if (required_mon_width && (pb = strstr (fmt, "%b")))
{
if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2))
{
char *pfmt = rpl_fmt;
nfmt = rpl_fmt;
pfmt = mempcpy (pfmt, fmt, pb - fmt);
pfmt = stpcpy (pfmt, abmon[tm->tm_mon]);
strcpy (pfmt, pb + 2);
}
}
size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns);
return ret;
}
/* Return the expected number of columns in a long-format time stamp,
or zero if it cannot be calculated. */
static int
long_time_expected_width (void)
{
static int width = -1;
if (width < 0)
{
time_t epoch = 0;
struct tm const *tm = localtime (&epoch);
char buf[TIME_STAMP_LEN_MAXIMUM + 1];
/* In case you're wondering if localtime can fail with an input time_t
value of 0, let's just say it's very unlikely, but not inconceivable.
The TZ environment variable would have to specify a time zone that
is 2**31-1900 years or more ahead of UTC. This could happen only on
a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
However, this is not possible with Solaris 10 or glibc-2.3.5, since
their implementations limit the offset to 167:59 and 24:00, resp. */
if (tm)
{
size_t len =
align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
if (len != 0)
width = mbsnwidth (buf, len, 0);
}
if (width < 0)
width = 0;
}
return width;
}
/* Print the user or group name NAME, with numeric id ID, using a
print width of WIDTH columns. */
static void
format_user_or_group (char const *name, unsigned long int id, int width)
{
size_t len;
if (name)
{
int width_gap = width - mbswidth (name, 0);
int pad = MAX (0, width_gap);
fputs (name, stdout);
len = strlen (name) + pad;
do
putchar (' ');
while (pad--);
}
else
{
printf ("%*lu ", width, id);
len = width;
}
dired_pos += len + 1;
}
/* Print the name or id of the user with id U, using a print width of
WIDTH. */
static void
format_user (uid_t u, int width, bool stat_ok)
{
format_user_or_group (! stat_ok ? "?" :
(numeric_ids ? NULL : getuser (u)), u, width);
}
/* Likewise, for groups. */
static void
format_group (gid_t g, int width, bool stat_ok)
{
format_user_or_group (! stat_ok ? "?" :
(numeric_ids ? NULL : getgroup (g)), g, width);
}
/* Return the number of columns that format_user_or_group will print. */
static int
format_user_or_group_width (char const *name, unsigned long int id)
{
if (name)
{
int len = mbswidth (name, 0);
return MAX (0, len);
}
else
{
char buf[INT_BUFSIZE_BOUND (id)];
sprintf (buf, "%lu", id);
return strlen (buf);
}
}
/* Return the number of columns that format_user will print. */
static int
format_user_width (uid_t u)
{
return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
}
/* Likewise, for groups. */
static int
format_group_width (gid_t g)
{
return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
}
/* Return a pointer to a formatted version of F->stat.st_ino,
possibly using buffer, BUF, of length BUFLEN, which must be at least
INT_BUFSIZE_BOUND (uintmax_t) bytes. */
static char *
format_inode (char *buf, size_t buflen, const struct fileinfo *f)
{
assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen);
return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
? umaxtostr (f->stat.st_ino, buf)
: (char *) "?");
}
/* Print information about F in long format. */
static void
print_long_format (const struct fileinfo *f)
{
char modebuf[12];
char buf
[LONGEST_HUMAN_READABLE + 1 /* inode */
+ LONGEST_HUMAN_READABLE + 1 /* size in blocks */
+ sizeof (modebuf) - 1 + 1 /* mode string */
+ INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
+ LONGEST_HUMAN_READABLE + 2 /* major device number */
+ LONGEST_HUMAN_READABLE + 1 /* minor device number */
+ TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
];
size_t s;
char *p;
struct timespec when_timespec;
struct tm *when_local;
/* Compute the mode string, except remove the trailing space if no
file in this directory has an ACL or SELinux security context. */
if (f->stat_ok)
filemodestring (&f->stat, modebuf);
else
{
modebuf[0] = filetype_letter[f->filetype];
memset (modebuf + 1, '?', 10);
modebuf[11] = '\0';
}
if (! any_has_acl)
modebuf[10] = '\0';
else if (f->acl_type == ACL_T_SELINUX_ONLY)
modebuf[10] = '.';
else if (f->acl_type == ACL_T_YES)
modebuf[10] = '+';
switch (time_type)
{
case time_ctime:
when_timespec = get_stat_ctime (&f->stat);
break;
case time_mtime:
when_timespec = get_stat_mtime (&f->stat);
break;
case time_atime:
when_timespec = get_stat_atime (&f->stat);
break;
default:
abort ();
}
p = buf;
if (print_inode)
{
char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
sprintf (p, "%*s ", inode_number_width,
format_inode (hbuf, sizeof hbuf, f));
/* Increment by strlen (p) here, rather than by inode_number_width + 1.
The latter is wrong when inode_number_width is zero. */
p += strlen (p);
}
if (print_block_size)
{
char hbuf[LONGEST_HUMAN_READABLE + 1];
char const *blocks =
(! f->stat_ok
? "?"
: human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
ST_NBLOCKSIZE, output_block_size));
int pad;
for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
*p++ = ' ';
while ((*p++ = *blocks++))
continue;
p[-1] = ' ';
}
/* The last byte of the mode string is the POSIX
"optional alternate access method flag". */
{
char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
sprintf (p, "%s %*s ", modebuf, nlink_width,
! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
}
/* Increment by strlen (p) here, rather than by, e.g.,
sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
The latter is wrong when nlink_width is zero. */
p += strlen (p);
DIRED_INDENT ();
if (print_owner || print_group || print_author || print_scontext)
{
DIRED_FPUTS (buf, stdout, p - buf);
if (print_owner)
format_user (f->stat.st_uid, owner_width, f->stat_ok);
if (print_group)
format_group (f->stat.st_gid, group_width, f->stat_ok);
if (print_author)
format_user (f->stat.st_author, author_width, f->stat_ok);
if (print_scontext)
format_user_or_group (f->scontext, 0, scontext_width);
p = buf;
}
if (f->stat_ok
&& (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
{
char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
int blanks_width = (file_size_width
- (major_device_number_width + 2
+ minor_device_number_width));
sprintf (p, "%*s, %*s ",
major_device_number_width + MAX (0, blanks_width),
umaxtostr (major (f->stat.st_rdev), majorbuf),
minor_device_number_width,
umaxtostr (minor (f->stat.st_rdev), minorbuf));
p += file_size_width + 1;
}
else
{
char hbuf[LONGEST_HUMAN_READABLE + 1];
char const *size =
(! f->stat_ok
? "?"
: human_readable (unsigned_file_size (f->stat.st_size),
hbuf, file_human_output_opts, 1,
file_output_block_size));
int pad;
for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
*p++ = ' ';
while ((*p++ = *size++))
continue;
p[-1] = ' ';
}
when_local = localtime (&when_timespec.tv_sec);
s = 0;
*p = '\1';
if (f->stat_ok && when_local)
{
struct timespec six_months_ago;
bool recent;
char const *fmt;
/* If the file appears to be in the future, update the current
time, in case the file happens to have been modified since
the last time we checked the clock. */
if (timespec_cmp (current_time, when_timespec) < 0)
{
/* Note that gettime may call gettimeofday which, on some non-
compliant systems, clobbers the buffer used for localtime's result.
But it's ok here, because we use a gettimeofday wrapper that
saves and restores the buffer around the gettimeofday call. */
gettime (¤t_time);
}
/* Consider a time to be recent if it is within the past six
months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
31556952 seconds on the average. Write this value as an
integer constant to avoid floating point hassles. */
six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
six_months_ago.tv_nsec = current_time.tv_nsec;
recent = (timespec_cmp (six_months_ago, when_timespec) < 0
&& (timespec_cmp (when_timespec, current_time) < 0));
fmt = long_time_format[recent];
/* We assume here that all time zones are offset from UTC by a
whole number of seconds. */
s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
when_local, 0, when_timespec.tv_nsec);
}
if (s || !*p)
{
p += s;
*p++ = ' ';
/* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
*p = '\0';
}
else
{
/* The time cannot be converted using the desired format, so
print it as a huge integer number of seconds. */
char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
sprintf (p, "%*s ", long_time_expected_width (),
(! f->stat_ok
? "?"
: timetostr (when_timespec.tv_sec, hbuf)));
/* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
p += strlen (p);
}
DIRED_FPUTS (buf, stdout, p - buf);
size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
if (f->filetype == symbolic_link)
{
if (f->linkname)
{
DIRED_FPUTS_LITERAL (" -> ", stdout);
print_name_with_quoting (f, true, NULL, (p - buf) + w + 4);
if (indicator_style != none)
print_type_indicator (true, f->linkmode, unknown);
}
}
else if (indicator_style != none)
print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
}
/* Output to OUT a quoted representation of the file name NAME,
using OPTIONS to control quoting. Produce no output if OUT is NULL.
Store the number of screen columns occupied by NAME's quoted
representation into WIDTH, if non-NULL. Return the number of bytes
produced. */
static size_t
quote_name (FILE *out, const char *name, struct quoting_options const *options,
size_t *width)
{
char smallbuf[BUFSIZ];
size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
char *buf;
size_t displayed_width IF_LINT ( = 0);
if (len < sizeof smallbuf)
buf = smallbuf;
else
{
buf = alloca (len + 1);
quotearg_buffer (buf, len + 1, name, -1, options);
}
if (qmark_funny_chars)
{
if (MB_CUR_MAX > 1)
{
char const *p = buf;
char const *plimit = buf + len;
char *q = buf;
displayed_width = 0;
while (p < plimit)
switch (*p)
{
case ' ': case '!': case '"': case '#': case '%':
case '&': case '\'': case '(': case ')': case '*':
case '+': case ',': case '-': case '.': case '/':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case ':': case ';': case '<': case '=': case '>':
case '?':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
case '[': case '\\': case ']': case '^': case '_':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z': case '{': case '|': case '}': case '~':
/* These characters are printable ASCII characters. */
*q++ = *p++;
displayed_width += 1;
break;
default:
/* If we have a multibyte sequence, copy it until we
reach its end, replacing each non-printable multibyte
character with a single question mark. */
{
mbstate_t mbstate = { 0, };
do
{
wchar_t wc;
size_t bytes;
int w;
bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
if (bytes == (size_t) -1)
{
/* An invalid multibyte sequence was
encountered. Skip one input byte, and
put a question mark. */
p++;
*q++ = '?';
displayed_width += 1;
break;
}
if (bytes == (size_t) -2)
{
/* An incomplete multibyte character
at the end. Replace it entirely with
a question mark. */
p = plimit;
*q++ = '?';
displayed_width += 1;
break;
}
if (bytes == 0)
/* A null wide character was encountered. */
bytes = 1;
w = wcwidth (wc);
if (w >= 0)
{
/* A printable multibyte character.
Keep it. */
for (; bytes > 0; --bytes)
*q++ = *p++;
displayed_width += w;
}
else
{
/* An unprintable multibyte character.
Replace it entirely with a question
mark. */
p += bytes;
*q++ = '?';
displayed_width += 1;
}
}
while (! mbsinit (&mbstate));
}
break;
}
/* The buffer may have shrunk. */
len = q - buf;
}
else
{
char *p = buf;
char const *plimit = buf + len;
while (p < plimit)
{
if (! isprint (to_uchar (*p)))
*p = '?';
p++;
}
displayed_width = len;
}
}
else if (width != NULL)
{
if (MB_CUR_MAX > 1)
displayed_width = mbsnwidth (buf, len, 0);
else
{
char const *p = buf;
char const *plimit = buf + len;
displayed_width = 0;
while (p < plimit)
{
if (isprint (to_uchar (*p)))
displayed_width++;
p++;
}
}
}
if (out != NULL)
fwrite (buf, 1, len, out);
if (width != NULL)
*width = displayed_width;
return len;
}
static size_t
print_name_with_quoting (const struct fileinfo *f,
bool symlink_target,
struct obstack *stack,
size_t start_col)
{
const char* name = symlink_target ? f->linkname : f->name;
bool used_color_this_time
= (print_with_color
&& (print_color_indicator (f, symlink_target)
|| is_colored (C_NORM)));
if (stack)
PUSH_CURRENT_DIRED_POS (stack);
size_t width = quote_name (stdout, name, filename_quoting_options, NULL);
dired_pos += width;
if (stack)
PUSH_CURRENT_DIRED_POS (stack);
process_signals ();
if (used_color_this_time)
{
prep_non_filename_text ();
if (start_col / line_length != (start_col + width - 1) / line_length)
put_indicator (&color_indicator[C_CLR_TO_EOL]);
}
return width;
}
static void
prep_non_filename_text (void)
{
if (color_indicator[C_END].string != NULL)
put_indicator (&color_indicator[C_END]);
else
{
put_indicator (&color_indicator[C_LEFT]);
put_indicator (&color_indicator[C_RESET]);
put_indicator (&color_indicator[C_RIGHT]);
}
}
/* Print the file name of 'f' with appropriate quoting.
Also print file size, inode number, and filetype indicator character,
as requested by switches. */
static size_t
print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
{
char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
set_normal_color ();
if (print_inode)
printf ("%*s ", format == with_commas ? 0 : inode_number_width,
format_inode (buf, sizeof buf, f));
if (print_block_size)
printf ("%*s ", format == with_commas ? 0 : block_size_width,
! f->stat_ok ? "?"
: human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
ST_NBLOCKSIZE, output_block_size));
if (print_scontext)
printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
size_t width = print_name_with_quoting (f, false, NULL, start_col);
if (indicator_style != none)
width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
return width;
}
/* Given these arguments describing a file, return the single-byte
type indicator, or 0. */
static char
get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
{
char c;
if (stat_ok ? S_ISREG (mode) : type == normal)
{
if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
c = '*';
else
c = 0;
}
else
{
if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
c = '/';
else if (indicator_style == slash)
c = 0;
else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
c = '@';
else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
c = '|';
else if (stat_ok ? S_ISSOCK (mode) : type == sock)
c = '=';
else if (stat_ok && S_ISDOOR (mode))
c = '>';
else
c = 0;
}
return c;
}
static bool
print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
{
char c = get_type_indicator (stat_ok, mode, type);
if (c)
DIRED_PUTCHAR (c);
return !!c;
}
/* Returns whether any color sequence was printed. */
static bool
print_color_indicator (const struct fileinfo *f, bool symlink_target)
{
enum indicator_no type;
struct color_ext_type *ext; /* Color extension */
size_t len; /* Length of name */
const char* name;
mode_t mode;
int linkok;
if (symlink_target)
{
name = f->linkname;
mode = f->linkmode;
linkok = f->linkok ? 0 : -1;
}
else
{
name = f->name;
mode = FILE_OR_LINK_MODE (f);
linkok = f->linkok;
}
/* Is this a nonexistent file? If so, linkok == -1. */
if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
type = C_MISSING;
else if (!f->stat_ok)
{
static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
type = filetype_indicator[f->filetype];
}
else
{
if (S_ISREG (mode))
{
type = C_FILE;
if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
type = C_SETUID;
else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
type = C_SETGID;
else if (is_colored (C_CAP) && f->has_capability)
type = C_CAP;
else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
type = C_EXEC;
else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
type = C_MULTIHARDLINK;
}
else if (S_ISDIR (mode))
{
type = C_DIR;
if ((mode & S_ISVTX) && (mode & S_IWOTH)
&& is_colored (C_STICKY_OTHER_WRITABLE))
type = C_STICKY_OTHER_WRITABLE;
else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
type = C_OTHER_WRITABLE;
else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
type = C_STICKY;
}
else if (S_ISLNK (mode))
type = C_LINK;
else if (S_ISFIFO (mode))
type = C_FIFO;
else if (S_ISSOCK (mode))
type = C_SOCK;
else if (S_ISBLK (mode))
type = C_BLK;
else if (S_ISCHR (mode))
type = C_CHR;
else if (S_ISDOOR (mode))
type = C_DOOR;
else
{
/* Classify a file of some other type as C_ORPHAN. */
type = C_ORPHAN;
}
}
/* Check the file's suffix only if still classified as C_FILE. */
ext = NULL;
if (type == C_FILE)
{
/* Test if NAME has a recognized suffix. */
len = strlen (name);
name += len; /* Pointer to final \0. */
for (ext = color_ext_list; ext != NULL; ext = ext->next)
{
if (ext->ext.len <= len
&& STREQ_LEN (name - ext->ext.len, ext->ext.string,
ext->ext.len))
break;
}
}
/* Adjust the color for orphaned symlinks. */
if (type == C_LINK && !linkok)
{
if (color_symlink_as_referent
|| color_indicator[C_ORPHAN].string)
type = C_ORPHAN;
}
{
const struct bin_str *const s
= ext ? &(ext->seq) : &color_indicator[type];
if (s->string != NULL)
{
/* Need to reset so not dealing with attribute combinations */
if (is_colored (C_NORM))
restore_default_color ();
put_indicator (&color_indicator[C_LEFT]);
put_indicator (s);
put_indicator (&color_indicator[C_RIGHT]);
return true;
}
else
return false;
}
}
/* Output a color indicator (which may contain nulls). */
static void
put_indicator (const struct bin_str *ind)
{
if (! used_color)
{
used_color = true;
prep_non_filename_text ();
}
fwrite (ind->string, ind->len, 1, stdout);
}
static size_t
length_of_file_name_and_frills (const struct fileinfo *f)
{
size_t len = 0;
size_t name_width;
char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
if (print_inode)
len += 1 + (format == with_commas
? strlen (umaxtostr (f->stat.st_ino, buf))
: inode_number_width);
if (print_block_size)
len += 1 + (format == with_commas
? strlen (! f->stat_ok ? "?"
: human_readable (ST_NBLOCKS (f->stat), buf,
human_output_opts, ST_NBLOCKSIZE,
output_block_size))
: block_size_width);
if (print_scontext)
len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
quote_name (NULL, f->name, filename_quoting_options, &name_width);
len += name_width;
if (indicator_style != none)
{
char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
len += (c != 0);
}
return len;
}
static void
print_many_per_line (void)
{
size_t row; /* Current row. */
size_t cols = calculate_columns (true);
struct column_info const *line_fmt = &column_info[cols - 1];
/* Calculate the number of rows that will be in each column except possibly
for a short column on the right. */
size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
for (row = 0; row < rows; row++)
{
size_t col = 0;
size_t filesno = row;
size_t pos = 0;
/* Print the next row. */
while (1)
{
struct fileinfo const *f = sorted_file[filesno];
size_t name_length = length_of_file_name_and_frills (f);
size_t max_name_length = line_fmt->col_arr[col++];
print_file_name_and_frills (f, pos);
filesno += rows;
if (filesno >= cwd_n_used)
break;
indent (pos + name_length, pos + max_name_length);
pos += max_name_length;
}
putchar ('\n');
}
}
static void
print_horizontal (void)
{
size_t filesno;
size_t pos = 0;
size_t cols = calculate_columns (false);
struct column_info const *line_fmt = &column_info[cols - 1];
struct fileinfo const *f = sorted_file[0];
size_t name_length = length_of_file_name_and_frills (f);
size_t max_name_length = line_fmt->col_arr[0];
/* Print first entry. */
print_file_name_and_frills (f, 0);
/* Now the rest. */
for (filesno = 1; filesno < cwd_n_used; ++filesno)
{
size_t col = filesno % cols;
if (col == 0)
{
putchar ('\n');
pos = 0;
}
else
{
indent (pos + name_length, pos + max_name_length);
pos += max_name_length;
}
f = sorted_file[filesno];
print_file_name_and_frills (f, pos);
name_length = length_of_file_name_and_frills (f);
max_name_length = line_fmt->col_arr[col];
}
putchar ('\n');
}
static void
print_with_commas (void)
{
size_t filesno;
size_t pos = 0;
for (filesno = 0; filesno < cwd_n_used; filesno++)
{
struct fileinfo const *f = sorted_file[filesno];
size_t len = length_of_file_name_and_frills (f);
if (filesno != 0)
{
char separator;
if (pos + len + 2 < line_length)
{
pos += 2;
separator = ' ';
}
else
{
pos = 0;
separator = '\n';
}
putchar (',');
putchar (separator);
}
print_file_name_and_frills (f, pos);
pos += len;
}
putchar ('\n');
}
/* Assuming cursor is at position FROM, indent up to position TO.
Use a TAB character instead of two or more spaces whenever possible. */
static void
indent (size_t from, size_t to)
{
while (from < to)
{
if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
{
putchar ('\t');
from += tabsize - from % tabsize;
}
else
{
putchar (' ');
from++;
}
}
}
/* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
/* FIXME: maybe remove this function someday. See about using a
non-malloc'ing version of file_name_concat. */
static void
attach (char *dest, const char *dirname, const char *name)
{
const char *dirnamep = dirname;
/* Copy dirname if it is not ".". */
if (dirname[0] != '.' || dirname[1] != 0)
{
while (*dirnamep)
*dest++ = *dirnamep++;
/* Add '/' if 'dirname' doesn't already end with it. */
if (dirnamep > dirname && dirnamep[-1] != '/')
*dest++ = '/';
}
while (*name)
*dest++ = *name++;
*dest = 0;
}
/* Allocate enough column info suitable for the current number of
files and display columns, and initialize the info to represent the
narrowest possible columns. */
static void
init_column_info (void)
{
size_t i;
size_t max_cols = MIN (max_idx, cwd_n_used);
/* Currently allocated columns in column_info. */
static size_t column_info_alloc;
if (column_info_alloc < max_cols)
{
size_t new_column_info_alloc;
size_t *p;
if (max_cols < max_idx / 2)
{
/* The number of columns is far less than the display width
allows. Grow the allocation, but only so that it's
double the current requirements. If the display is
extremely wide, this avoids allocating a lot of memory
that is never needed. */
column_info = xnrealloc (column_info, max_cols,
2 * sizeof *column_info);
new_column_info_alloc = 2 * max_cols;
}
else
{
column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
new_column_info_alloc = max_idx;
}
/* Allocate the new size_t objects by computing the triangle
formula n * (n + 1) / 2, except that we don't need to
allocate the part of the triangle that we've already
allocated. Check for address arithmetic overflow. */
{
size_t column_info_growth = new_column_info_alloc - column_info_alloc;
size_t s = column_info_alloc + 1 + new_column_info_alloc;
size_t t = s * column_info_growth;
if (s < new_column_info_alloc || t / column_info_growth != s)
xalloc_die ();
p = xnmalloc (t / 2, sizeof *p);
}
/* Grow the triangle by parceling out the cells just allocated. */
for (i = column_info_alloc; i < new_column_info_alloc; i++)
{
column_info[i].col_arr = p;
p += i + 1;
}
column_info_alloc = new_column_info_alloc;
}
for (i = 0; i < max_cols; ++i)
{
size_t j;
column_info[i].valid_len = true;
column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
for (j = 0; j <= i; ++j)
column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
}
}
/* Calculate the number of columns needed to represent the current set
of files in the current display width. */
static size_t
calculate_columns (bool by_columns)
{
size_t filesno; /* Index into cwd_file. */
size_t cols; /* Number of files across. */
/* Normally the maximum number of columns is determined by the
screen width. But if few files are available this might limit it
as well. */
size_t max_cols = MIN (max_idx, cwd_n_used);
init_column_info ();
/* Compute the maximum number of possible columns. */
for (filesno = 0; filesno < cwd_n_used; ++filesno)
{
struct fileinfo const *f = sorted_file[filesno];
size_t name_length = length_of_file_name_and_frills (f);
size_t i;
for (i = 0; i < max_cols; ++i)
{
if (column_info[i].valid_len)
{
size_t idx = (by_columns
? filesno / ((cwd_n_used + i) / (i + 1))
: filesno % (i + 1));
size_t real_length = name_length + (idx == i ? 0 : 2);
if (column_info[i].col_arr[idx] < real_length)
{
column_info[i].line_len += (real_length
- column_info[i].col_arr[idx]);
column_info[i].col_arr[idx] = real_length;
column_info[i].valid_len = (column_info[i].line_len
< line_length);
}
}
}
}
/* Find maximum allowed columns. */
for (cols = max_cols; 1 < cols; --cols)
{
if (column_info[cols - 1].valid_len)
break;
}
return cols;
}
void
usage (int status)
{
if (status != EXIT_SUCCESS)
emit_try_help ();
else
{
printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
fputs (_("\
List information about the FILEs (the current directory by default).\n\
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
\n\
"), stdout);
fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
fputs (_("\
-a, --all do not ignore entries starting with .\n\
-A, --almost-all do not list implied . and ..\n\
--author with -l, print the author of each file\n\
-b, --escape print C-style escapes for nongraphic characters\n\
"), stdout);
fputs (_("\
--block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
'--block-size=M' prints sizes in units of\n\
1,048,576 bytes. See SIZE format below.\n\
-B, --ignore-backups do not list implied entries ending with ~\n\
-c with -lt: sort by, and show, ctime (time of last\n\
modification of file status information)\n\
with -l: show ctime and sort by name\n\
otherwise: sort by ctime, newest first\n\
"), stdout);
fputs (_("\
-C list entries by columns\n\
--color[=WHEN] colorize the output. WHEN defaults to 'always'\n\
or can be 'never' or 'auto'. More info below\n\
-d, --directory list directory entries instead of contents,\n\
and do not dereference symbolic links\n\
-D, --dired generate output designed for Emacs' dired mode\n\
"), stdout);
fputs (_("\
-f do not sort, enable -aU, disable -ls --color\n\
-F, --classify append indicator (one of */=>@|) to entries\n\
--file-type likewise, except do not append '*'\n\
--format=WORD across -x, commas -m, horizontal -x, long -l,\n\
single-column -1, verbose -l, vertical -C\n\
--full-time like -l --time-style=full-iso\n\
"), stdout);
fputs (_("\
-g like -l, but do not list owner\n\
"), stdout);
fputs (_("\
--group-directories-first\n\
group directories before files.\n\
augment with a --sort option, but any\n\
use of --sort=none (-U) disables grouping\n\
"), stdout);
fputs (_("\
-G, --no-group in a long listing, don't print group names\n\
-h, --human-readable with -l, print sizes in human readable format\n\
(e.g., 1K 234M 2G)\n\
--si likewise, but use powers of 1000 not 1024\n\
"), stdout);
fputs (_("\
-H, --dereference-command-line\n\
follow symbolic links listed on the command line\n\
--dereference-command-line-symlink-to-dir\n\
follow each command line symbolic link\n\
that points to a directory\n\
--hide=PATTERN do not list implied entries matching shell PATTERN\
\n\
(overridden by -a or -A)\n\
"), stdout);
fputs (_("\
--indicator-style=WORD append indicator with style WORD to entry names:\
\n\
none (default), slash (-p),\n\
file-type (--file-type), classify (-F)\n\
-i, --inode print the index number of each file\n\
-I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
\n\
-k, --kibibytes use 1024-byte blocks\n\
"), stdout);
fputs (_("\
-l use a long listing format\n\
-L, --dereference when showing file information for a symbolic\n\
link, show information for the file the link\n\
references rather than for the link itself\n\
-m fill width with a comma separated list of entries\
\n\
"), stdout);
fputs (_("\
-n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
-N, --literal print raw entry names (don't treat e.g. control\n\
characters specially)\n\
-o like -l, but do not list group information\n\
-p, --indicator-style=slash\n\
append / indicator to directories\n\
"), stdout);
fputs (_("\
-q, --hide-control-chars print ? instead of non graphic characters\n\
--show-control-chars show non graphic characters as-is (default\n\
unless program is 'ls' and output is a terminal)\n\
-Q, --quote-name enclose entry names in double quotes\n\
--quoting-style=WORD use quoting style WORD for entry names:\n\
literal, locale, shell, shell-always, c, escape\
\n\
"), stdout);
fputs (_("\
-r, --reverse reverse order while sorting\n\
-R, --recursive list subdirectories recursively\n\
-s, --size print the allocated size of each file, in blocks\n\
"), stdout);
fputs (_("\
-S sort by file size\n\
--sort=WORD sort by WORD instead of name: none -U,\n\
extension -X, size -S, time -t, version -v\n\
--time=WORD with -l, show time as WORD instead of modification\
\n\
time: atime -u, access -u, use -u, ctime -c,\n\
or status -c; use specified time as sort key\n\
if --sort=time\n\
"), stdout);
fputs (_("\
--time-style=STYLE with -l, show times using style STYLE:\n\
full-iso, long-iso, iso, locale, +FORMAT.\n\
FORMAT is interpreted like 'date'; if FORMAT is\n\
FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
non-recent files and FORMAT2 to recent files;\n\
if STYLE is prefixed with 'posix-', STYLE\n\
takes effect only outside the POSIX locale\n\
"), stdout);
fputs (_("\
-t sort by modification time, newest first\n\
-T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
"), stdout);
fputs (_("\
-u with -lt: sort by, and show, access time\n\
with -l: show access time and sort by name\n\
otherwise: sort by access time\n\
-U do not sort; list entries in directory order\n\
-v natural sort of (version) numbers within text\n\
"), stdout);
fputs (_("\
-w, --width=COLS assume screen width instead of current value\n\
-x list entries by lines instead of by columns\n\
-X sort alphabetically by entry extension\n\
-Z, --context print any SELinux security context of each file\n\
-1 list one file per line\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
emit_size_note ();
fputs (_("\
\n\
Using color to distinguish file types is disabled both by default and\n\
with --color=never. With --color=auto, ls emits color codes only when\n\
standard output is connected to a terminal. The LS_COLORS environment\n\
variable can change the settings. Use the dircolors command to set it.\n\
"), stdout);
fputs (_("\
\n\
Exit status:\n\
0 if OK,\n\
1 if minor problems (e.g., cannot access subdirectory),\n\
2 if serious trouble (e.g., cannot access command-line argument).\n\
"), stdout);
emit_ancillary_info ();
}
exit (status);
}
|