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
|
/*
* builtin.c - Builtin functions and various utility procedures.
*/
/*
* Copyright (C) 1986, 1988, 1989, 1991-2019 the Free Software Foundation, Inc.
*
* This file is part of GAWK, the GNU implementation of the
* AWK Programming Language.
*
* GAWK 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.
*
* GAWK 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "awk.h"
#if defined(HAVE_FCNTL_H)
#include <fcntl.h>
#endif
#include <math.h>
#include "random.h"
#include "floatmagic.h"
#if defined(HAVE_POPEN_H)
#include "popen.h"
#endif
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
/* The extra casts work around common compiler bugs. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
/* Note: these assume that negative integers are represented internally
via 2's complement, which is not mandated by C. They also ignore the
fact that signed integer arithmetic overflow can trigger exceptions,
unlike unsigned which is guaranteed not to do so. */
#define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
? ~ (uintmax_t) 0 << (sizeof (t) * CHAR_BIT - 1) \
: 0))
#define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
#ifndef INTMAX_MIN
# define INTMAX_MIN TYPE_MINIMUM (intmax_t)
#endif
#ifndef UINTMAX_MAX
# define UINTMAX_MAX TYPE_MAXIMUM (uintmax_t)
#endif
#ifndef SIZE_MAX /* C99 constant, can't rely on it everywhere */
#define SIZE_MAX ((size_t) -1)
#endif
#define DEFAULT_G_PRECISION 6
static size_t mbc_byte_count(const char *ptr, size_t numchars);
static size_t mbc_char_count(const char *ptr, size_t numbytes);
/* Can declare these, since we always use the random shipped with gawk */
extern char *initstate(unsigned long seed, char *state, long n);
extern char *setstate(char *state);
extern long random(void);
extern void srandom(unsigned long seed);
extern NODE **args_array;
extern int max_args;
extern NODE **fields_arr;
extern bool output_is_tty;
extern FILE *output_fp;
#define POP_TWO_SCALARS(s1, s2) \
s2 = POP_SCALAR(); \
s1 = POP(); \
do { if (s1->type == Node_var_array) { \
DEREF(s2); \
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(s1)); \
}} while (false)
/*
* Since we supply the version of random(), we know what
* value to use here.
*/
#define GAWK_RANDOM_MAX 0x7fffffffL
/* efwrite --- like fwrite, but with error checking */
static void
efwrite(const void *ptr,
size_t size,
size_t count,
FILE *fp,
const char *from,
struct redirect *rp,
bool flush)
{
errno = 0;
if (rp != NULL) {
if (rp->output.gawk_fwrite(ptr, size, count, fp, rp->output.opaque) != count)
goto wrerror;
} else if (fwrite(ptr, size, count, fp) != count)
goto wrerror;
if (flush
&& ((fp == stdout && output_is_tty)
|| (rp != NULL && (rp->flag & RED_NOBUF) != 0))) {
if (rp != NULL) {
rp->output.gawk_fflush(fp, rp->output.opaque);
if (rp->output.gawk_ferror(fp, rp->output.opaque))
goto wrerror;
} else {
fflush(fp);
if (ferror(fp))
goto wrerror;
}
}
return;
wrerror:
#ifdef __MINGW32__
if (errno == 0 || errno == EINVAL)
w32_maybe_set_errno();
#endif
/* for stdout, die with a real SIGPIPE, like other awks */
if (fp == stdout && errno == EPIPE)
die_via_sigpipe();
/* otherwise die verbosely */
if ((rp != NULL) ? is_non_fatal_redirect(rp->value, strlen(rp->value)) : is_non_fatal_std(fp))
update_ERRNO_int(errno);
else
fatal(_("%s to \"%s\" failed (%s)"), from,
rp != NULL
? rp->value
: fp == stdout
? _("standard output")
: _("standard error"),
errno ? strerror(errno) : _("reason unknown"));
}
/* do_exp --- exponential function */
NODE *
do_exp(int nargs)
{
NODE *tmp;
double d, res;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("exp: received non-numeric argument"));
d = force_number(tmp)->numbr;
DEREF(tmp);
errno = 0;
res = exp(d);
if (errno == ERANGE)
warning(_("exp: argument %g is out of range"), d);
return make_number((AWKNUM) res);
}
/* stdfile --- return fp for a standard file */
/*
* This function allows `fflush("/dev/stdout")' to work.
* The other files will be available via getredirect().
* /dev/stdin is not included, since fflush is only for output.
*/
static FILE *
stdfile(const char *name, size_t len)
{
if (len == 11) {
if (strncmp(name, "/dev/stderr", 11) == 0)
return stderr;
else if (strncmp(name, "/dev/stdout", 11) == 0)
return stdout;
}
return NULL;
}
/* do_fflush --- flush output, either named file or pipe or everything */
NODE *
do_fflush(int nargs)
{
struct redirect *rp;
NODE *tmp;
FILE *fp;
int status = 0;
const char *file;
int len;
/*
* November, 2012.
* It turns out that circa 2002, when BWK
* added fflush() and fflush("") to his awk, he made both of
* them flush everything.
*
* Now, with our inside agent getting ready to try to get fflush()
* standardized in POSIX, we are going to make our awk consistent
* with his. This should not really affect anyone, as flushing
* everything also flushes stdout.
*
* So. Once upon a time:
* fflush() --- flush stdout
* fflush("") --- flush everything
* Now, both calls flush everything.
*/
/* fflush() */
if (nargs == 0) {
status = flush_io(); // ERRNO updated
return make_number((AWKNUM) status);
}
tmp = POP_STRING();
file = tmp->stptr;
len = tmp->stlen;
/* fflush("") */
if (tmp->stlen == 0) {
status = flush_io(); // ERRNO updated
DEREF(tmp);
return make_number((AWKNUM) status);
}
/* fflush("/some/path") */
rp = getredirect(tmp->stptr, tmp->stlen);
status = -1;
if (rp != NULL) {
if ((rp->flag & (RED_WRITE|RED_APPEND)) == 0) {
if ((rp->flag & RED_PIPE) != 0)
warning(_("fflush: cannot flush: pipe `%.*s' opened for reading, not writing"),
len, file);
else
warning(_("fflush: cannot flush: file `%.*s' opened for reading, not writing"),
len, file);
DEREF(tmp);
return make_number((AWKNUM) status);
}
fp = rp->output.fp;
if (fp != NULL) {
status = rp->output.gawk_fflush(fp, rp->output.opaque);
if (status != 0) {
if (! is_non_fatal_redirect(tmp->stptr, tmp->stlen))
fatal(_("fflush: cannot flush file `%.*s': %s"),
len, file, strerror(errno));
update_ERRNO_int(errno);
}
} else if ((rp->flag & RED_TWOWAY) != 0)
warning(_("fflush: cannot flush: two-way pipe `%.*s' has closed write end"),
len, file);
} else if ((fp = stdfile(tmp->stptr, tmp->stlen)) != NULL) {
status = (non_fatal_flush_std_file(fp) == false);
} else {
status = -1;
warning(_("fflush: `%.*s' is not an open file, pipe or co-process"), len, file);
}
DEREF(tmp);
return make_number((AWKNUM) status);
}
/* strncasecmpmbs --- like strncasecmp (multibyte string version) */
int
strncasecmpmbs(const unsigned char *s1, const unsigned char *s2, size_t n)
{
size_t i1, i2, mbclen1, mbclen2, gap;
wchar_t wc1, wc2;
mbstate_t mbs1, mbs2;
memset(& mbs1, 0, sizeof(mbs1));
memset(& mbs2, 0, sizeof(mbs2));
for (i1 = i2 = 0 ; i1 < n && i2 < n ;i1 += mbclen1, i2 += mbclen2) {
if (is_valid_character(s1[i1])) {
mbclen1 = 1;
wc1 = btowc_cache(s1[i1]);
} else {
mbclen1 = mbrtowc(& wc1, (const char *)s1 + i1,
n - i1, & mbs1);
if (mbclen1 == (size_t) -1 || mbclen1 == (size_t) -2 || mbclen1 == 0) {
/* We treat it as a singlebyte character. */
mbclen1 = 1;
wc1 = btowc_cache(s1[i1]);
}
}
if (is_valid_character(s2[i2])) {
mbclen2 = 1;
wc2 = btowc_cache(s2[i2]);
} else {
mbclen2 = mbrtowc(& wc2, (const char *)s2 + i2,
n - i2, & mbs2);
if (mbclen2 == (size_t) -1 || mbclen2 == (size_t) -2 || mbclen2 == 0) {
/* We treat it as a singlebyte character. */
mbclen2 = 1;
wc2 = btowc_cache(s2[i2]);
}
}
if ((gap = towlower(wc1) - towlower(wc2)) != 0)
/* s1 and s2 are not equivalent. */
return gap;
}
/* s1 and s2 are equivalent. */
return 0;
}
/* Inspect the buffer `src' and write the index of each byte to `dest'.
Caller must allocate `dest'.
e.g. str = <mb1(1)>, <mb1(2)>, a, b, <mb2(1)>, <mb2(2)>, <mb2(3)>, c
where mb(i) means the `i'-th byte of a multibyte character.
dest = 1, 2, 1, 1, 1, 2, 3. 1
*/
static void
index_multibyte_buffer(char* src, char* dest, int len)
{
int idx, prev_idx;
mbstate_t mbs, prevs;
memset(& prevs, 0, sizeof(mbstate_t));
for (idx = prev_idx = 0 ; idx < len ; idx++) {
size_t mbclen;
mbs = prevs;
mbclen = mbrlen(src + prev_idx, idx - prev_idx + 1, & mbs);
if (mbclen == (size_t) -1 || mbclen == 1 || mbclen == 0) {
/* singlebyte character. */
mbclen = 1;
prev_idx = idx + 1;
} else if (mbclen == (size_t) -2) {
/* a part of a multibyte character. */
mbclen = idx - prev_idx + 1;
} else if (mbclen > 1) {
/* the end of a multibyte character. */
prev_idx = idx + 1;
prevs = mbs;
} else {
/* Can't reach. */
}
dest[idx] = mbclen;
}
}
/* do_index --- find index of a string */
NODE *
do_index(int nargs)
{
NODE *s1, *s2;
const char *p1, *p2;
size_t l1, l2;
long ret;
bool do_single_byte = false;
mbstate_t mbs1, mbs2;
if (gawk_mb_cur_max > 1) {
memset(& mbs1, 0, sizeof(mbstate_t));
memset(& mbs2, 0, sizeof(mbstate_t));
}
POP_TWO_SCALARS(s1, s2);
if (do_lint) {
if ((fixtype(s1)->flags & STRING) == 0)
lintwarn(_("index: received non-string first argument"));
if ((fixtype(s2)->flags & STRING) == 0)
lintwarn(_("index: received non-string second argument"));
}
s1 = force_string(s1);
s2 = force_string(s2);
p1 = s1->stptr;
p2 = s2->stptr;
l1 = s1->stlen;
l2 = s2->stlen;
ret = 0;
/*
* Icky special case, index(foo, "") should return 1,
* since both bwk awk and mawk do, and since match("foo", "")
* returns 1. This makes index("", "") work, too, fwiw.
*/
if (l2 == 0) {
ret = 1;
goto out;
}
if (gawk_mb_cur_max > 1) {
s1 = force_wstring(s1);
s2 = force_wstring(s2);
/*
* If we don't have valid wide character strings, use
* the real bytes.
*/
do_single_byte = ((s1->wstlen == 0 && s1->stlen > 0)
|| (s2->wstlen == 0 && s2->stlen > 0));
}
/* IGNORECASE will already be false if posix */
if (IGNORECASE) {
while (l1 > 0) {
if (l2 > l1)
break;
if (! do_single_byte && gawk_mb_cur_max > 1) {
const wchar_t *pos;
pos = wcasestrstr(s1->wstptr, s1->wstlen, s2->wstptr, s2->wstlen);
if (pos == NULL)
ret = 0;
else
ret = pos - s1->wstptr + 1; /* 1-based */
goto out;
} else {
/*
* Could use tolower(*p1) == tolower(*p2) here.
* See discussion in eval.c as to why not.
*/
if (casetable[(unsigned char)*p1] == casetable[(unsigned char)*p2]
&& (l2 == 1 || strncasecmp(p1, p2, l2) == 0)) {
ret = 1 + s1->stlen - l1;
break;
}
l1--;
p1++;
}
}
} else {
while (l1 > 0) {
if (l2 > l1)
break;
if (*p1 == *p2
&& (l2 == 1 || (l2 > 0 && memcmp(p1, p2, l2) == 0))) {
ret = 1 + s1->stlen - l1;
break;
}
if (! do_single_byte && gawk_mb_cur_max > 1) {
const wchar_t *pos;
pos = wstrstr(s1->wstptr, s1->wstlen, s2->wstptr, s2->wstlen);
if (pos == NULL)
ret = 0;
else
ret = pos - s1->wstptr + 1; /* 1-based */
goto out;
} else {
l1--;
p1++;
}
}
}
out:
DEREF(s1);
DEREF(s2);
return make_number((AWKNUM) ret);
}
/* double_to_int --- convert double to int, used several places */
double
double_to_int(double d)
{
if (d >= 0)
d = floor(d);
else
d = ceil(d);
return d;
}
/* do_int --- convert double to int for awk */
NODE *
do_int(int nargs)
{
NODE *tmp;
double d;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("int: received non-numeric argument"));
d = force_number(tmp)->numbr;
d = double_to_int(d);
DEREF(tmp);
return make_number((AWKNUM) d);
}
/* do_isarray --- check if argument is array */
NODE *
do_isarray(int nargs)
{
NODE *tmp;
int ret = 1;
tmp = POP();
if (tmp->type != Node_var_array) {
ret = 0;
// could be Node_var_new
if (tmp->type == Node_val)
DEREF(tmp);
}
return make_number((AWKNUM) ret);
}
/* do_length --- length of a string, array or $0 */
NODE *
do_length(int nargs)
{
NODE *tmp;
size_t len;
tmp = POP();
if (tmp->type == Node_var_array) {
static bool warned = false;
unsigned long size;
if (do_posix)
fatal(_("length: received array argument"));
if (do_lint_extensions && ! warned) {
warned = true;
lintwarn(_("`length(array)' is a gawk extension"));
}
/*
* Support for deferred loading of array elements requires that
* we use the array length interface even though it isn't
* necessary for the built-in array types.
*
* 1/2015: The deferred arrays are gone, but this is probably
* still a good idea.
*/
size = assoc_length(tmp);
return make_number(size);
}
assert(tmp->type == Node_val);
if (do_lint && (fixtype(tmp)->flags & STRING) == 0)
lintwarn(_("length: received non-string argument"));
tmp = force_string(tmp);
if (gawk_mb_cur_max > 1) {
tmp = force_wstring(tmp);
len = tmp->wstlen;
/*
* If the bytes don't make a valid wide character
* string, fall back to the bytes themselves.
*/
if (len == 0 && tmp->stlen > 0)
len = tmp->stlen;
} else
len = tmp->stlen;
DEREF(tmp);
return make_number((AWKNUM) len);
}
/* do_log --- the log function */
NODE *
do_log(int nargs)
{
NODE *tmp;
double d, arg;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("log: received non-numeric argument"));
arg = force_number(tmp)->numbr;
if (arg < 0.0)
warning(_("log: received negative argument %g"), arg);
d = log(arg);
DEREF(tmp);
return make_number((AWKNUM) d);
}
#ifdef HAVE_MPFR
/*
* mpz2mpfr --- convert an arbitrary-precision integer to a float
* without any loss of precision. The returned value is only
* good for temporary use.
*/
static mpfr_ptr
mpz2mpfr(mpz_ptr zi)
{
size_t prec;
static mpfr_t mpfrval;
static bool inited = false;
int tval;
/* estimate minimum precision for exact conversion */
prec = mpz_sizeinbase(zi, 2); /* most significant 1 bit position starting at 1 */
prec -= (size_t) mpz_scan1(zi, 0); /* least significant 1 bit index starting at 0 */
if (prec < MPFR_PREC_MIN)
prec = MPFR_PREC_MIN;
else if (prec > MPFR_PREC_MAX)
prec = MPFR_PREC_MAX;
if (! inited) {
mpfr_init2(mpfrval, prec);
inited = true;
} else
mpfr_set_prec(mpfrval, prec);
tval = mpfr_set_z(mpfrval, zi, ROUND_MODE);
IEEE_FMT(mpfrval, tval);
return mpfrval;
}
#endif
/*
* format_tree() formats arguments of sprintf,
* and accordingly to a fmt_string providing a format like in
* printf family from C library. Returns a string node which value
* is a formatted string. Called by sprintf function.
*
* It is one of the uglier parts of gawk. Thanks to Michal Jaegermann
* for taming this beast and making it compatible with ANSI C.
*/
NODE *
format_tree(
const char *fmt_string,
size_t n0,
NODE **the_args,
long num_args)
{
/* copy 'l' bytes from 's' to 'obufout' checking for space in the process */
/* difference of pointers should be of ptrdiff_t type, but let us be kind */
#define bchunk(s, l) if (l) { \
while ((l) > ofre) { \
size_t olen = obufout - obuf; \
erealloc(obuf, char *, osiz * 2, "format_tree"); \
ofre += osiz; \
osiz *= 2; \
obufout = obuf + olen; \
} \
memcpy(obufout, s, (size_t) (l)); \
obufout += (l); \
ofre -= (l); \
}
/* copy one byte from 's' to 'obufout' checking for space in the process */
#define bchunk_one(s) { \
if (ofre < 1) { \
size_t olen = obufout - obuf; \
erealloc(obuf, char *, osiz * 2, "format_tree"); \
ofre += osiz; \
osiz *= 2; \
obufout = obuf + olen; \
} \
*obufout++ = *s; \
--ofre; \
}
/* Is there space for something L big in the buffer? */
#define chksize(l) if ((l) >= ofre) { \
size_t olen = obufout - obuf; \
size_t delta = osiz+l-ofre; \
erealloc(obuf, char *, osiz + delta, "format_tree"); \
obufout = obuf + olen; \
ofre += delta; \
osiz += delta; \
}
size_t cur_arg = 0;
NODE *r = NULL;
int i, nc;
bool toofew = false;
char *obuf, *obufout;
size_t osiz, ofre, olen_final;
const char *chbuf;
const char *s0, *s1;
int cs1;
NODE *arg;
long fw, prec, argnum;
bool used_dollar;
bool lj, alt, big_flag, bigbig_flag, small_flag, have_prec, need_format;
long *cur = NULL;
uintmax_t uval;
bool sgn;
int base;
/*
* Although this is an array, the elements serve two different
* purposes. The first element is the general buffer meant
* to hold the entire result string. The second one is a
* temporary buffer for large floating point values. They
* could just as easily be separate variables, and the
* code might arguably be clearer.
*/
struct {
char *buf;
size_t bufsize;
char stackbuf[30];
} cpbufs[2];
#define cpbuf cpbufs[0].buf
char *cend = &cpbufs[0].stackbuf[sizeof(cpbufs[0].stackbuf)];
char *cp;
const char *fill;
AWKNUM tmpval = 0.0;
char signchar = '\0';
size_t len;
bool zero_flag = false;
bool quote_flag = false;
int ii, jj;
char *chp;
size_t copy_count, char_count;
char *nan_inf_val;
bool magic_posix_flag;
#ifdef HAVE_MPFR
mpz_ptr zi;
mpfr_ptr mf;
#endif
enum { MP_NONE = 0, MP_INT_WITH_PREC = 1, MP_INT_WITHOUT_PREC, MP_FLOAT } fmt_type;
static const char sp[] = " ";
static const char zero_string[] = "0";
static const char lchbuf[] = "0123456789abcdef";
static const char Uchbuf[] = "0123456789ABCDEF";
#define INITIAL_OUT_SIZE 64
emalloc(obuf, char *, INITIAL_OUT_SIZE, "format_tree");
obufout = obuf;
osiz = INITIAL_OUT_SIZE;
ofre = osiz - 1;
cur_arg = 1;
{
size_t k;
for (k = 0; k < sizeof(cpbufs)/sizeof(cpbufs[0]); k++) {
cpbufs[k].bufsize = sizeof(cpbufs[k].stackbuf);
cpbufs[k].buf = cpbufs[k].stackbuf;
}
}
/*
* The point of this goop is to grow the buffer
* holding the converted number, so that large
* values don't overflow a fixed length buffer.
*/
#define PREPEND(CH) do { \
if (cp == cpbufs[0].buf) { \
char *prev = cpbufs[0].buf; \
emalloc(cpbufs[0].buf, char *, 2*cpbufs[0].bufsize, \
"format_tree"); \
memcpy((cp = cpbufs[0].buf+cpbufs[0].bufsize), prev, \
cpbufs[0].bufsize); \
cpbufs[0].bufsize *= 2; \
if (prev != cpbufs[0].stackbuf) \
efree(prev); \
cend = cpbufs[0].buf+cpbufs[0].bufsize; \
} \
*--cp = (CH); \
} while(0)
/*
* Check first for use of `count$'.
* If plain argument retrieval was used earlier, choke.
* Otherwise, return the requested argument.
* If not `count$' now, but it was used earlier, choke.
* If this format is more than total number of args, choke.
* Otherwise, return the current argument.
*/
#define parse_next_arg() { \
if (argnum > 0) { \
if (cur_arg > 1) { \
msg(_("fatal: must use `count$' on all formats or none")); \
goto out; \
} \
arg = the_args[argnum]; \
} else if (used_dollar) { \
msg(_("fatal: must use `count$' on all formats or none")); \
arg = 0; /* shutup the compiler */ \
goto out; \
} else if (cur_arg >= num_args) { \
arg = 0; /* shutup the compiler */ \
toofew = true; \
break; \
} else { \
arg = the_args[cur_arg]; \
cur_arg++; \
} \
}
need_format = false;
used_dollar = false;
s0 = s1 = fmt_string;
while (n0-- > 0) {
if (*s1 != '%') {
s1++;
continue;
}
need_format = true;
bchunk(s0, s1 - s0);
s0 = s1;
cur = &fw;
fw = 0;
prec = 0;
base = 0;
argnum = 0;
base = 0;
have_prec = false;
signchar = '\0';
zero_flag = false;
quote_flag = false;
nan_inf_val = NULL;
#ifdef HAVE_MPFR
mf = NULL;
zi = NULL;
#endif
fmt_type = MP_NONE;
lj = alt = big_flag = bigbig_flag = small_flag = false;
magic_posix_flag = false;
fill = sp;
cp = cend;
chbuf = lchbuf;
s1++;
retry:
if (n0-- == 0) /* ran out early! */
break;
switch (cs1 = *s1++) {
case (-1): /* dummy case to allow for checking */
check_pos:
if (cur != &fw)
break; /* reject as a valid format */
goto retry;
case '%':
need_format = false;
/*
* 29 Oct. 2002:
* The C99 standard pages 274 and 279 seem to imply that
* since there's no arg converted, the field width doesn't
* apply. The code already was that way, but this
* comment documents it, at least in the code.
*/
if (do_lint) {
const char *msg = NULL;
if (fw && ! have_prec)
msg = _("field width is ignored for `%%' specifier");
else if (fw == 0 && have_prec)
msg = _("precision is ignored for `%%' specifier");
else if (fw && have_prec)
msg = _("field width and precision are ignored for `%%' specifier");
if (msg != NULL)
lintwarn("%s", msg);
}
bchunk_one("%");
s0 = s1;
break;
case '0':
/*
* Only turn on zero_flag if we haven't seen
* the field width or precision yet. Otherwise,
* screws up floating point formatting.
*/
if (cur == & fw)
zero_flag = true;
if (lj)
goto retry;
/* FALL through */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (cur == NULL)
break;
if (prec >= 0)
*cur = cs1 - '0';
/*
* with a negative precision *cur is already set
* to -1, so it will remain negative, but we have
* to "eat" precision digits in any case
*/
while (n0 > 0 && *s1 >= '0' && *s1 <= '9') {
--n0;
*cur = *cur * 10 + *s1++ - '0';
}
if (prec < 0) /* negative precision is discarded */
have_prec = false;
if (cur == &prec)
cur = NULL;
if (n0 == 0) /* badly formatted control string */
continue;
goto retry;
case '$':
if (do_traditional) {
msg(_("fatal: `$' is not permitted in awk formats"));
goto out;
}
if (cur == &fw) {
argnum = fw;
fw = 0;
used_dollar = true;
if (argnum <= 0) {
msg(_("fatal: arg count with `$' must be > 0"));
goto out;
}
if (argnum >= num_args) {
msg(_("fatal: arg count %ld greater than total number of supplied arguments"), argnum);
goto out;
}
} else {
msg(_("fatal: `$' not permitted after period in format"));
goto out;
}
goto retry;
case '*':
if (cur == NULL)
break;
if (! do_traditional && used_dollar && ! isdigit((unsigned char) *s1)) {
fatal(_("fatal: must use `count$' on all formats or none"));
break; /* silence warnings */
} else if (! do_traditional && isdigit((unsigned char) *s1)) {
int val = 0;
for (; n0 > 0 && *s1 && isdigit((unsigned char) *s1); s1++, n0--) {
val *= 10;
val += *s1 - '0';
}
if (*s1 != '$') {
msg(_("fatal: no `$' supplied for positional field width or precision"));
goto out;
} else {
s1++;
n0--;
}
if (val >= num_args) {
toofew = true;
break;
}
arg = the_args[val];
} else {
parse_next_arg();
}
(void) force_number(arg);
*cur = get_number_si(arg);
if (*cur < 0 && cur == &fw) {
*cur = -*cur;
lj = true;
}
if (cur == &prec) {
if (*cur >= 0)
have_prec = true;
else
have_prec = false;
cur = NULL;
}
goto retry;
case ' ': /* print ' ' or '-' */
/* 'space' flag is ignored */
/* if '+' already present */
if (signchar != false)
goto check_pos;
/* FALL THROUGH */
case '+': /* print '+' or '-' */
signchar = cs1;
goto check_pos;
case '-':
if (prec < 0)
break;
if (cur == &prec) {
prec = -1;
goto retry;
}
fill = sp; /* if left justified then other */
lj = true; /* filling is ignored */
goto check_pos;
case '.':
if (cur != &fw)
break;
cur = ≺
have_prec = true;
goto retry;
case '#':
alt = true;
goto check_pos;
case '\'':
#if defined(HAVE_LOCALE_H)
quote_flag = true;
goto check_pos;
#else
goto retry;
#endif
case 'l':
if (big_flag)
break;
else {
static bool warned = false;
if (do_lint && ! warned) {
lintwarn(_("`l' is meaningless in awk formats; ignored"));
warned = true;
}
if (do_posix) {
msg(_("fatal: `l' is not permitted in POSIX awk formats"));
goto out;
}
}
big_flag = true;
goto retry;
case 'L':
if (bigbig_flag)
break;
else {
static bool warned = false;
if (do_lint && ! warned) {
lintwarn(_("`L' is meaningless in awk formats; ignored"));
warned = true;
}
if (do_posix) {
msg(_("fatal: `L' is not permitted in POSIX awk formats"));
goto out;
}
}
bigbig_flag = true;
goto retry;
case 'h':
if (small_flag)
break;
else {
static bool warned = false;
if (do_lint && ! warned) {
lintwarn(_("`h' is meaningless in awk formats; ignored"));
warned = true;
}
if (do_posix) {
msg(_("fatal: `h' is not permitted in POSIX awk formats"));
goto out;
}
}
small_flag = true;
goto retry;
case 'P':
if (magic_posix_flag)
break;
magic_posix_flag = true;
goto retry;
case 'c':
need_format = false;
parse_next_arg();
/* user input that looks numeric is numeric */
fixtype(arg);
if ((arg->flags & NUMBER) != 0) {
uval = get_number_uj(arg);
if (gawk_mb_cur_max > 1) {
char buf[100];
wchar_t wc;
mbstate_t mbs;
size_t count;
memset(& mbs, 0, sizeof(mbs));
/* handle systems with too small wchar_t */
if (sizeof(wchar_t) < 4 && uval > 0xffff) {
if (do_lint)
lintwarn(
_("[s]printf: value %g is too big for %%c format"),
arg->numbr);
goto out0;
}
wc = uval;
count = wcrtomb(buf, wc, & mbs);
if (count == 0
|| count == (size_t) -1) {
if (do_lint)
lintwarn(
_("[s]printf: value %g is not a valid wide character"),
arg->numbr);
goto out0;
}
memcpy(cpbuf, buf, count);
prec = count;
cp = cpbuf;
goto pr_tail;
}
out0:
;
/* else,
fall through */
cpbuf[0] = uval;
prec = 1;
cp = cpbuf;
goto pr_tail;
}
/*
* As per POSIX, only output first character of a
* string value. Thus, we ignore any provided
* precision, forcing it to 1. (Didn't this
* used to work? 6/2003.)
*/
cp = arg->stptr;
prec = 1;
/*
* First character can be multiple bytes if
* it's a multibyte character. Grr.
*/
if (gawk_mb_cur_max > 1) {
mbstate_t state;
size_t count;
memset(& state, 0, sizeof(state));
count = mbrlen(cp, arg->stlen, & state);
if (count != (size_t) -1 && count != (size_t) -2 && count > 0) {
prec = count;
/* may need to increase fw so that padding happens, see pr_tail code */
if (fw > 0)
fw += count - 1;
}
}
goto pr_tail;
case 's':
need_format = false;
parse_next_arg();
arg = force_string(arg);
if (fw == 0 && ! have_prec)
prec = arg->stlen;
else {
char_count = mbc_char_count(arg->stptr, arg->stlen);
if (! have_prec || prec > char_count)
prec = char_count;
}
cp = arg->stptr;
goto pr_tail;
case 'd':
case 'i':
need_format = false;
parse_next_arg();
(void) force_number(arg);
/*
* Check for Nan or Inf.
*/
if (out_of_range(arg))
goto out_of_range;
#ifdef HAVE_MPFR
if (is_mpg_float(arg))
goto mpf0;
else if (is_mpg_integer(arg))
goto mpz0;
else
#endif
tmpval = double_to_int(arg->numbr);
/*
* ``The result of converting a zero value with a
* precision of zero is no characters.''
*/
if (have_prec && prec == 0 && tmpval == 0)
goto pr_tail;
if (tmpval < 0) {
tmpval = -tmpval;
sgn = true;
} else {
if (tmpval == -0.0)
/* avoid printing -0 */
tmpval = 0.0;
sgn = false;
}
/*
* Use snprintf return value to tell if there
* is enough room in the buffer or not.
*/
while ((i = snprintf(cpbufs[1].buf,
cpbufs[1].bufsize, "%.0f",
tmpval)) >=
cpbufs[1].bufsize) {
if (cpbufs[1].buf == cpbufs[1].stackbuf)
cpbufs[1].buf = NULL;
if (i > 0) {
cpbufs[1].bufsize += ((i > cpbufs[1].bufsize) ?
i : cpbufs[1].bufsize);
}
else
cpbufs[1].bufsize *= 2;
assert(cpbufs[1].bufsize > 0);
erealloc(cpbufs[1].buf, char *,
cpbufs[1].bufsize, "format_tree");
}
if (i < 1)
goto out_of_range;
#if defined(HAVE_LOCALE_H)
quote_flag = (quote_flag && loc.thousands_sep[0] != 0);
#endif
chp = &cpbufs[1].buf[i-1];
ii = jj = 0;
do {
PREPEND(*chp);
chp--; i--;
#if defined(HAVE_LOCALE_H)
if (quote_flag && loc.grouping[ii] && ++jj == loc.grouping[ii]) {
if (i) { /* only add if more digits coming */
int k;
const char *ts = loc.thousands_sep;
for (k = strlen(ts) - 1; k >= 0; k--) {
PREPEND(ts[k]);
}
}
if (loc.grouping[ii+1] == 0)
jj = 0; /* keep using current val in loc.grouping[ii] */
else if (loc.grouping[ii+1] == CHAR_MAX)
quote_flag = false;
else {
ii++;
jj = 0;
}
}
#endif
} while (i > 0);
/* add more output digits to match the precision */
if (have_prec) {
while (cend - cp < prec)
PREPEND('0');
}
if (sgn)
PREPEND('-');
else if (signchar)
PREPEND(signchar);
/*
* When to fill with zeroes is of course not simple.
* First: No zero fill if left-justifying.
* Next: There seem to be two cases:
* A '0' without a precision, e.g. %06d
* A precision with no field width, e.g. %.10d
* Any other case, we don't want to fill with zeroes.
*/
if (! lj
&& ((zero_flag && ! have_prec)
|| (fw == 0 && have_prec)))
fill = zero_string;
if (prec > fw)
fw = prec;
prec = cend - cp;
if (fw > prec && ! lj && fill != sp
&& (*cp == '-' || signchar)) {
bchunk_one(cp);
cp++;
prec--;
fw--;
}
goto pr_tail;
case 'X':
chbuf = Uchbuf; /* FALL THROUGH */
case 'x':
base += 6; /* FALL THROUGH */
case 'u':
base += 2; /* FALL THROUGH */
case 'o':
base += 8;
need_format = false;
parse_next_arg();
(void) force_number(arg);
if (out_of_range(arg))
goto out_of_range;
#ifdef HAVE_MPFR
if (is_mpg_integer(arg)) {
mpz0:
zi = arg->mpg_i;
if (cs1 != 'd' && cs1 != 'i') {
if (mpz_sgn(zi) <= 0) {
/*
* Negative value or 0 requires special handling.
* Unlike MPFR, GMP does not allow conversion
* to (u)intmax_t. So we first convert GMP type to
* a MPFR type.
*/
mf = mpz2mpfr(zi);
goto mpf1;
}
signchar = '\0'; /* Don't print '+' */
}
/* See comments above about when to fill with zeros */
zero_flag = (! lj
&& ((zero_flag && ! have_prec)
|| (fw == 0 && have_prec)));
fmt_type = have_prec ? MP_INT_WITH_PREC : MP_INT_WITHOUT_PREC;
goto fmt0;
} else if (is_mpg_float(arg)) {
mpf0:
mf = arg->mpg_numbr;
if (! mpfr_number_p(mf)) {
/* inf or NaN */
cs1 = 'g';
fmt_type = MP_FLOAT;
goto fmt1;
}
if (cs1 != 'd' && cs1 != 'i') {
mpf1:
/*
* The output of printf("%#.0x", 0) is 0 instead of 0x, hence <= in
* the comparison below.
*/
if (mpfr_sgn(mf) <= 0) {
if (! mpfr_fits_intmax_p(mf, ROUND_MODE)) {
/* -ve number is too large */
cs1 = 'g';
fmt_type = MP_FLOAT;
goto fmt1;
}
tmpval = uval = (uintmax_t) mpfr_get_sj(mf, ROUND_MODE);
if (! alt && have_prec && prec == 0 && tmpval == 0)
goto pr_tail; /* printf("%.0x", 0) is no characters */
goto int0;
}
signchar = '\0'; /* Don't print '+' */
}
/* See comments above about when to fill with zeros */
zero_flag = (! lj
&& ((zero_flag && ! have_prec)
|| (fw == 0 && have_prec)));
(void) mpfr_get_z(mpzval, mf, MPFR_RNDZ); /* convert to GMP integer */
fmt_type = have_prec ? MP_INT_WITH_PREC : MP_INT_WITHOUT_PREC;
zi = mpzval;
goto fmt0;
} else
#endif
tmpval = arg->numbr;
/*
* ``The result of converting a zero value with a
* precision of zero is no characters.''
*
* If I remember the ANSI C standard, though,
* it says that for octal conversions
* the precision is artificially increased
* to add an extra 0 if # is supplied.
* Indeed, in C,
* printf("%#.0o\n", 0);
* prints a single 0.
*/
if (! alt && have_prec && prec == 0 && tmpval == 0)
goto pr_tail;
if (tmpval < 0) {
uval = (uintmax_t) (intmax_t) tmpval;
if ((AWKNUM)(intmax_t)uval != double_to_int(tmpval))
goto out_of_range;
} else {
uval = (uintmax_t) tmpval;
if ((AWKNUM)uval != double_to_int(tmpval))
goto out_of_range;
}
#ifdef HAVE_MPFR
int0:
#endif
#if defined(HAVE_LOCALE_H)
quote_flag = (quote_flag && loc.thousands_sep[0] != 0);
#endif
/*
* When to fill with zeroes is of course not simple.
* First: No zero fill if left-justifying.
* Next: There seem to be two cases:
* A '0' without a precision, e.g. %06d
* A precision with no field width, e.g. %.10d
* Any other case, we don't want to fill with zeroes.
*/
if (! lj
&& ((zero_flag && ! have_prec)
|| (fw == 0 && have_prec)))
fill = zero_string;
ii = jj = 0;
do {
PREPEND(chbuf[uval % base]);
uval /= base;
#if defined(HAVE_LOCALE_H)
if (base == 10 && quote_flag && loc.grouping[ii] && ++jj == loc.grouping[ii]) {
if (uval) { /* only add if more digits coming */
int k;
const char *ts = loc.thousands_sep;
for (k = strlen(ts) - 1; k >= 0; k--) {
PREPEND(ts[k]);
}
}
if (loc.grouping[ii+1] == 0)
jj = 0; /* keep using current val in loc.grouping[ii] */
else if (loc.grouping[ii+1] == CHAR_MAX)
quote_flag = false;
else {
ii++;
jj = 0;
}
}
#endif
} while (uval > 0);
/* add more output digits to match the precision */
if (have_prec) {
while (cend - cp < prec)
PREPEND('0');
}
if (alt && tmpval != 0) {
if (base == 16) {
PREPEND(cs1);
PREPEND('0');
if (fill != sp) {
bchunk(cp, 2);
cp += 2;
fw -= 2;
}
} else if (base == 8)
PREPEND('0');
}
base = 0;
if (prec > fw)
fw = prec;
prec = cend - cp;
pr_tail:
if (! lj) {
while (fw > prec) {
bchunk_one(fill);
fw--;
}
}
copy_count = prec;
if (fw == 0 && ! have_prec)
;
else if (gawk_mb_cur_max > 1) {
if (cs1 == 's') {
assert(cp == arg->stptr || cp == cpbuf);
copy_count = mbc_byte_count(arg->stptr, prec);
}
/* prec was set by code for %c */
/* else
copy_count = prec; */
}
bchunk(cp, copy_count);
while (fw > prec) {
bchunk_one(fill);
fw--;
}
s0 = s1;
break;
out_of_range:
/*
* out of range - emergency use of %g format,
* or format NaN and INF values.
*/
nan_inf_val = format_nan_inf(arg, cs1);
if (do_posix || magic_posix_flag || nan_inf_val == NULL) {
if (do_lint && ! do_posix && ! magic_posix_flag)
lintwarn(_("[s]printf: value %g is out of range for `%%%c' format"),
(double) tmpval, cs1);
tmpval = arg->numbr;
if (strchr("aAeEfFgG", cs1) == NULL)
cs1 = 'g';
goto fmt1;
} else {
if (do_lint)
lintwarn(_("[s]printf: value %s is out of range for `%%%c' format"),
nan_inf_val, cs1);
bchunk(nan_inf_val, strlen(nan_inf_val));
s0 = s1;
break;
}
case 'F':
#if ! defined(PRINTF_HAS_F_FORMAT) || PRINTF_HAS_F_FORMAT != 1
cs1 = 'f';
/* FALL THROUGH */
#endif
case 'g':
case 'G':
case 'e':
case 'f':
case 'E':
#if defined(PRINTF_HAS_A_FORMAT) && PRINTF_HAS_A_FORMAT == 1
case 'A':
case 'a':
{
static bool warned = false;
if (do_lint && tolower(cs1) == 'a' && ! warned) {
warned = true;
lintwarn(_("%%%c format is POSIX standard but not portable to other awks"), cs1);
}
}
#endif
need_format = false;
parse_next_arg();
(void) force_number(arg);
if (! is_mpg_number(arg))
tmpval = arg->numbr;
#ifdef HAVE_MPFR
else if (is_mpg_float(arg)) {
mf = arg->mpg_numbr;
fmt_type = MP_FLOAT;
} else {
/* arbitrary-precision integer, convert to MPFR float */
assert(mf == NULL);
mf = mpz2mpfr(arg->mpg_i);
fmt_type = MP_FLOAT;
}
#endif
if (out_of_range(arg))
goto out_of_range;
fmt1:
if (! have_prec)
prec = DEFAULT_G_PRECISION;
#ifdef HAVE_MPFR
fmt0:
#endif
chksize(fw + prec + 11); /* 11 == slop */
cp = cpbuf;
*cp++ = '%';
if (lj)
*cp++ = '-';
if (signchar)
*cp++ = signchar;
if (alt)
*cp++ = '#';
if (zero_flag)
*cp++ = '0';
if (quote_flag)
*cp++ = '\'';
#if defined(LC_NUMERIC)
if (quote_flag && ! use_lc_numeric)
setlocale(LC_NUMERIC, "");
#endif
switch (fmt_type) {
#ifdef HAVE_MPFR
case MP_INT_WITH_PREC:
sprintf(cp, "*.*Z%c", cs1);
while ((nc = mpfr_snprintf(obufout, ofre, cpbuf,
(int) fw, (int) prec, zi)) >= ofre)
chksize(nc)
break;
case MP_INT_WITHOUT_PREC:
sprintf(cp, "*Z%c", cs1);
while ((nc = mpfr_snprintf(obufout, ofre, cpbuf,
(int) fw, zi)) >= ofre)
chksize(nc)
break;
case MP_FLOAT:
sprintf(cp, "*.*R*%c", cs1);
while ((nc = mpfr_snprintf(obufout, ofre, cpbuf,
(int) fw, (int) prec, ROUND_MODE, mf)) >= ofre)
chksize(nc)
break;
#endif
default:
if (have_prec || tolower(cs1) != 'a') {
sprintf(cp, "*.*%c", cs1);
while ((nc = snprintf(obufout, ofre, cpbuf,
(int) fw, (int) prec,
(double) tmpval)) >= ofre)
chksize(nc)
} else {
// For %a and %A, use the default precision if it
// wasn't supplied by the user.
sprintf(cp, "*%c", cs1);
while ((nc = snprintf(obufout, ofre, cpbuf,
(int) fw,
(double) tmpval)) >= ofre)
chksize(nc)
}
}
#if defined(LC_NUMERIC)
if (quote_flag && ! use_lc_numeric)
setlocale(LC_NUMERIC, "C");
#endif
len = strlen(obufout);
ofre -= len;
obufout += len;
s0 = s1;
break;
default:
if (do_lint && is_alpha(cs1))
lintwarn(_("ignoring unknown format specifier character `%c': no argument converted"), cs1);
break;
}
if (toofew) {
msg("%s\n\t`%s'\n\t%*s%s",
_("fatal: not enough arguments to satisfy format string"),
fmt_string, (int) (s1 - fmt_string - 1), "",
_("^ ran out for this one"));
goto out;
}
}
if (do_lint) {
if (need_format)
lintwarn(
_("[s]printf: format specifier does not have control letter"));
if (cur_arg < num_args)
lintwarn(
_("too many arguments supplied for format string"));
}
bchunk(s0, s1 - s0);
olen_final = obufout - obuf;
#define GIVE_BACK_SIZE (INITIAL_OUT_SIZE * 2)
if (ofre > GIVE_BACK_SIZE)
erealloc(obuf, char *, olen_final + 1, "format_tree");
r = make_str_node(obuf, olen_final, ALREADY_MALLOCED);
obuf = NULL;
out:
{
size_t k;
size_t count = sizeof(cpbufs)/sizeof(cpbufs[0]);
for (k = 0; k < count; k++) {
if (cpbufs[k].buf != cpbufs[k].stackbuf)
efree(cpbufs[k].buf);
}
if (obuf != NULL)
efree(obuf);
}
if (r == NULL)
gawk_exit(EXIT_FATAL);
return r;
}
/* printf_common --- common code for sprintf and printf */
static NODE *
printf_common(int nargs)
{
int i;
NODE *r, *tmp;
assert(nargs > 0 && nargs <= max_args);
for (i = 1; i <= nargs; i++) {
tmp = args_array[nargs - i] = POP();
if (tmp->type == Node_var_array) {
while (--i > 0)
DEREF(args_array[nargs - i]);
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(tmp));
}
}
args_array[0] = force_string(args_array[0]);
r = format_tree(args_array[0]->stptr, args_array[0]->stlen, args_array, nargs);
for (i = 0; i < nargs; i++)
DEREF(args_array[i]);
return r;
}
/* do_sprintf --- perform sprintf */
NODE *
do_sprintf(int nargs)
{
NODE *r;
if (nargs == 0)
fatal(_("sprintf: no arguments"));
r = printf_common(nargs);
if (r == NULL)
gawk_exit(EXIT_FATAL);
return r;
}
/* do_printf --- perform printf, including redirection */
void
do_printf(int nargs, int redirtype)
{
FILE *fp = NULL;
NODE *tmp;
struct redirect *rp = NULL;
int errflg = 0;
NODE *redir_exp = NULL;
if (nargs == 0) {
if (do_traditional) {
if (do_lint)
lintwarn(_("printf: no arguments"));
if (redirtype != 0) {
redir_exp = TOP();
if (redir_exp->type != Node_val)
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(redir_exp));
rp = redirect(redir_exp, redirtype, & errflg, true);
DEREF(redir_exp);
decr_sp();
}
return; /* bwk accepts it silently */
}
fatal(_("printf: no arguments"));
}
if (redirtype != 0) {
redir_exp = PEEK(nargs);
if (redir_exp->type != Node_val)
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(redir_exp));
rp = redirect(redir_exp, redirtype, & errflg, true);
if (rp != NULL) {
if ((rp->flag & RED_TWOWAY) != 0 && rp->output.fp == NULL) {
if (is_non_fatal_redirect(redir_exp->stptr, redir_exp->stlen)) {
update_ERRNO_int(EBADF);
return;
}
(void) close_rp(rp, CLOSE_ALL);
fatal(_("printf: attempt to write to closed write end of two-way pipe"));
}
fp = rp->output.fp;
}
else if (errflg) {
update_ERRNO_int(errflg);
return;
}
} else if (do_debug) /* only the debugger can change the default output */
fp = output_fp;
else
fp = stdout;
tmp = printf_common(nargs);
if (redir_exp != NULL) {
DEREF(redir_exp);
decr_sp();
}
if (tmp != NULL) {
if (fp == NULL) {
DEREF(tmp);
return;
}
efwrite(tmp->stptr, sizeof(char), tmp->stlen, fp, "printf", rp, true);
if (rp != NULL && (rp->flag & RED_TWOWAY) != 0)
rp->output.gawk_fflush(rp->output.fp, rp->output.opaque);
DEREF(tmp);
} else
gawk_exit(EXIT_FATAL);
}
/* do_sqrt --- do the sqrt function */
NODE *
do_sqrt(int nargs)
{
NODE *tmp;
double arg;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("sqrt: received non-numeric argument"));
arg = (double) force_number(tmp)->numbr;
DEREF(tmp);
if (arg < 0.0)
warning(_("sqrt: called with negative argument %g"), arg);
return make_number((AWKNUM) sqrt(arg));
}
/* do_substr --- do the substr function */
NODE *
do_substr(int nargs)
{
NODE *t1;
NODE *r;
size_t indx;
size_t length = 0;
double d_index = 0, d_length = 0;
size_t src_len;
if (nargs == 3) {
t1 = POP_NUMBER();
d_length = get_number_d(t1);
DEREF(t1);
}
t1 = POP_NUMBER();
d_index = get_number_d(t1);
DEREF(t1);
t1 = POP_STRING();
if (nargs == 3) {
if (! (d_length >= 1)) {
if (do_lint == DO_LINT_ALL)
lintwarn(_("substr: length %g is not >= 1"), d_length);
else if (do_lint == DO_LINT_INVALID && ! (d_length >= 0))
lintwarn(_("substr: length %g is not >= 0"), d_length);
DEREF(t1);
/*
* Return explicit null string instead of doing
* dupnode(Nnull_string) so that if the result
* is checked with the combination of length()
* and lint, no error is reported about using
* an uninitialized value. Same thing later, too.
*/
return make_string("", 0);
}
if (do_lint) {
if (double_to_int(d_length) != d_length)
lintwarn(
_("substr: non-integer length %g will be truncated"),
d_length);
if (d_length > SIZE_MAX)
lintwarn(
_("substr: length %g too big for string indexing, truncating to %g"),
d_length, (double) SIZE_MAX);
}
if (d_length < SIZE_MAX)
length = d_length;
else
length = SIZE_MAX;
}
/* the weird `! (foo)' tests help catch NaN values. */
if (! (d_index >= 1)) {
if (do_lint)
lintwarn(_("substr: start index %g is invalid, using 1"),
d_index);
d_index = 1;
}
if (do_lint && double_to_int(d_index) != d_index)
lintwarn(_("substr: non-integer start index %g will be truncated"),
d_index);
/* awk indices are from 1, C's are from 0 */
if (d_index <= SIZE_MAX)
indx = d_index - 1;
else
indx = SIZE_MAX;
if (nargs == 2) { /* third arg. missing */
/* use remainder of string */
length = t1->stlen - indx; /* default to bytes */
if (gawk_mb_cur_max > 1) {
t1 = force_wstring(t1);
if (t1->wstlen > 0) /* use length of wide char string if we have one */
length = t1->wstlen - indx;
}
d_length = length; /* set here in case used in diagnostics, below */
}
if (t1->stlen == 0) {
/* substr("", 1, 0) produces a warning only if LINT_ALL */
if (do_lint && (do_lint == DO_LINT_ALL || ((indx | length) != 0)))
lintwarn(_("substr: source string is zero length"));
DEREF(t1);
return make_string("", 0);
}
/* get total len of input string, for following checks */
if (gawk_mb_cur_max > 1) {
t1 = force_wstring(t1);
src_len = t1->wstlen;
} else
src_len = t1->stlen;
if (indx >= src_len) {
if (do_lint)
lintwarn(_("substr: start index %g is past end of string"),
d_index);
DEREF(t1);
return make_string("", 0);
}
if (length > src_len - indx) {
if (do_lint)
lintwarn(
_("substr: length %g at start index %g exceeds length of first argument (%lu)"),
d_length, d_index, (unsigned long int) src_len);
length = src_len - indx;
}
/* force_wstring() already called */
if (gawk_mb_cur_max == 1 || t1->wstlen == t1->stlen)
/* single byte case */
r = make_string(t1->stptr + indx, length);
else {
/* multibyte case, more work */
size_t result;
wchar_t *wp;
mbstate_t mbs;
char *substr, *cp;
/*
* Convert the wide chars in t1->wstptr back into m.b. chars.
* This is pretty grotty, but it's the most straightforward
* way to do things.
*/
memset(& mbs, 0, sizeof(mbs));
emalloc(substr, char *, (length * gawk_mb_cur_max) + 1, "do_substr");
wp = t1->wstptr + indx;
for (cp = substr; length > 0; length--) {
result = wcrtomb(cp, *wp, & mbs);
if (result == (size_t) -1) /* what to do? break seems best */
break;
cp += result;
wp++;
}
*cp = '\0';
r = make_str_node(substr, cp - substr, ALREADY_MALLOCED);
}
DEREF(t1);
return r;
}
/* do_strftime --- format a time stamp */
NODE *
do_strftime(int nargs)
{
NODE *t1, *t2, *t3, *ret;
struct tm *tm;
time_t fclock;
double clock_val;
char *bufp;
size_t buflen, bufsize;
char buf[BUFSIZ];
const char *format;
int formatlen;
bool do_gmt;
NODE *val = NULL;
NODE *sub = NULL;
char save = '\0'; // initialize to avoid compiler warnings
static const time_t time_t_min = TYPE_MINIMUM(time_t);
static const time_t time_t_max = TYPE_MAXIMUM(time_t);
/* set defaults first */
format = def_strftime_format; /* traditional date format */
formatlen = strlen(format);
(void) time(& fclock); /* current time of day */
do_gmt = false;
if (PROCINFO_node != NULL) {
sub = make_string("strftime", 8);
val = in_array(PROCINFO_node, sub);
unref(sub);
if (val != NULL) {
if (do_lint && (fixtype(val)->flags & STRING) == 0)
lintwarn(_("strftime: format value in PROCINFO[\"strftime\"] has numeric type"));
val = force_string(val);
format = val->stptr;
formatlen = val->stlen;
}
}
t1 = t2 = t3 = NULL;
if (nargs > 0) { /* have args */
NODE *tmp;
if (nargs == 3) {
t3 = POP_SCALAR();
do_gmt = boolval(t3);
DEREF(t3);
}
if (nargs >= 2) {
t2 = POP_SCALAR();
if (do_lint && (fixtype(t2)->flags & NUMBER) == 0)
lintwarn(_("strftime: received non-numeric second argument"));
(void) force_number(t2);
clock_val = get_number_d(t2);
fclock = (time_t) clock_val;
/*
* Protect against negative value being assigned
* to unsigned time_t.
*/
if (clock_val < 0 && fclock > 0) {
if (do_lint)
lintwarn(_("strftime: second argument less than 0 or too big for time_t"));
return make_string("", 0);
}
/* And check that the value is in range */
if (clock_val < time_t_min || clock_val > time_t_max) {
if (do_lint)
lintwarn(_("strftime: second argument out of range for time_t"));
return make_string("", 0);
}
DEREF(t2);
}
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & STRING) == 0)
lintwarn(_("strftime: received non-string first argument"));
t1 = force_string(tmp);
format = t1->stptr;
formatlen = t1->stlen;
if (formatlen == 0) {
if (do_lint)
lintwarn(_("strftime: received empty format string"));
DEREF(t1);
return make_string("", 0);
}
str_terminate(t1, save);
}
if (do_gmt)
tm = gmtime(& fclock);
else
tm = localtime(& fclock);
if (tm == NULL) {
ret = make_string("", 0);
goto done;
}
bufp = buf;
bufsize = sizeof(buf);
for (;;) {
*bufp = '\0';
buflen = strftime(bufp, bufsize, format, tm);
/*
* buflen can be zero EITHER because there's not enough
* room in the string, or because the control command
* goes to the empty string. Make a reasonable guess that
* if the buffer is 1024 times bigger than the length of the
* format string, it's not failing for lack of room.
* Thanks to Paul Eggert for pointing out this issue.
*/
if (buflen > 0 || bufsize >= 1024 * formatlen)
break;
bufsize *= 2;
if (bufp == buf)
emalloc(bufp, char *, bufsize, "do_strftime");
else
erealloc(bufp, char *, bufsize, "do_strftime");
}
ret = make_string(bufp, buflen);
if (bufp != buf)
efree(bufp);
done:
if (t1) {
str_restore(t1, save);
DEREF(t1);
}
return ret;
}
/* do_systime --- get the time of day */
NODE *
do_systime(int nargs ATTRIBUTE_UNUSED)
{
time_t lclock;
(void) time(& lclock);
return make_number((AWKNUM) lclock);
}
/* do_mktime --- turn a time string into a timestamp */
NODE *
do_mktime(int nargs)
{
NODE *t1, *t2;
struct tm then;
long year;
int month, day, hour, minute, second, count;
int dst = -1; /* default is unknown */
time_t then_stamp;
char save;
bool do_gmt;
if (nargs == 2) {
t2 = POP_SCALAR();
do_gmt = boolval(t2);
DEREF(t2);
}
else
do_gmt = false;
t1 = POP_SCALAR();
if (do_lint && (fixtype(t1)->flags & STRING) == 0)
lintwarn(_("mktime: received non-string argument"));
t1 = force_string(t1);
save = t1->stptr[t1->stlen];
t1->stptr[t1->stlen] = '\0';
count = sscanf(t1->stptr, "%ld %d %d %d %d %d %d",
& year, & month, & day,
& hour, & minute, & second,
& dst);
if ( do_lint /* Ready? Set! Go: */
&& ( (second < 0 || second > 60)
|| (minute < 0 || minute > 59)
|| (hour < 0 || hour > 23) /* FIXME ISO 8601 allows 24 ? */
|| (day < 1 || day > 31)
|| (month < 1 || month > 12) ))
lintwarn(_("mktime: at least one of the values is out of the default range"));
t1->stptr[t1->stlen] = save;
DEREF(t1);
if (count < 6
|| month == INT_MIN
|| year < INT_MIN + 1900
|| year - 1900 > INT_MAX)
return make_number((AWKNUM) -1);
memset(& then, '\0', sizeof(then));
then.tm_sec = second;
then.tm_min = minute;
then.tm_hour = hour;
then.tm_mday = day;
then.tm_mon = month - 1;
then.tm_year = year - 1900;
then.tm_isdst = dst;
then_stamp = (do_gmt ? timegm(& then) : mktime(& then));
return make_number((AWKNUM) then_stamp);
}
/* do_system --- run an external command */
NODE *
do_system(int nargs)
{
NODE *tmp;
AWKNUM ret = 0; /* floating point on purpose, compat Unix awk */
char *cmd;
char save;
int status;
if (do_sandbox)
fatal(_("'system' function not allowed in sandbox mode"));
(void) flush_io(); /* so output is synchronous with gawk's */
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & STRING) == 0)
lintwarn(_("system: received non-string argument"));
cmd = force_string(tmp)->stptr;
if (cmd && *cmd) {
/* insure arg to system is zero-terminated */
save = cmd[tmp->stlen];
cmd[tmp->stlen] = '\0';
os_restore_mode(fileno(stdin));
set_sigpipe_to_default();
status = system(cmd);
/*
* 3/2016. What to do with ret? It's never simple.
* POSIX says to use the full return value. BWK awk
* divides the result by 256. That normally gives the
* exit status but gives a weird result for death-by-signal.
* So we compromise as follows:
*/
ret = status;
if (status != -1) {
if (do_posix)
; /* leave it alone, full 16 bits */
else if (do_traditional)
#ifdef __MINGW32__
ret = (((unsigned)status) & ~0xC0000000);
#else
ret = (status / 256.0);
#endif
else
ret = sanitize_exit_status(status);
}
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(fileno(stdin), O_BINARY);
ignore_sigpipe();
cmd[tmp->stlen] = save;
}
DEREF(tmp);
return make_number((AWKNUM) ret);
}
/* do_print --- print items, separated by OFS, terminated with ORS */
void
do_print(int nargs, int redirtype)
{
struct redirect *rp = NULL;
int errflg = 0;
FILE *fp = NULL;
int i;
NODE *redir_exp = NULL;
NODE *tmp = NULL;
assert(nargs <= max_args);
if (redirtype != 0) {
redir_exp = PEEK(nargs);
if (redir_exp->type != Node_val)
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(redir_exp));
rp = redirect(redir_exp, redirtype, & errflg, true);
if (rp != NULL) {
if ((rp->flag & RED_TWOWAY) != 0 && rp->output.fp == NULL) {
if (is_non_fatal_redirect(redir_exp->stptr, redir_exp->stlen)) {
update_ERRNO_int(EBADF);
return;
}
(void) close_rp(rp, CLOSE_ALL);
fatal(_("print: attempt to write to closed write end of two-way pipe"));
}
fp = rp->output.fp;
}
else if (errflg) {
update_ERRNO_int(errflg);
return;
}
} else if (do_debug) /* only the debugger can change the default output */
fp = output_fp;
else
fp = stdout;
for (i = 1; i <= nargs; i++) {
tmp = args_array[i] = POP();
if (tmp->type == Node_var_array) {
while (--i > 0)
DEREF(args_array[i]);
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(tmp));
}
// Let force_string_ofmt handle checking if things
// are already valid.
args_array[i] = force_string_ofmt(tmp);
}
if (redir_exp != NULL) {
DEREF(redir_exp);
decr_sp();
}
if (fp == NULL) {
for (i = nargs; i > 0; i--)
DEREF(args_array[i]);
return;
}
for (i = nargs; i > 0; i--) {
efwrite(args_array[i]->stptr, sizeof(char), args_array[i]->stlen, fp, "print", rp, false);
DEREF(args_array[i]);
if (i != 1 && OFSlen > 0)
efwrite(OFS, sizeof(char), (size_t) OFSlen,
fp, "print", rp, false);
}
if (ORSlen > 0)
efwrite(ORS, sizeof(char), (size_t) ORSlen, fp, "print", rp, true);
if (rp != NULL && (rp->flag & RED_TWOWAY) != 0)
rp->output.gawk_fflush(rp->output.fp, rp->output.opaque);
}
/* do_print_rec --- special case printing of $0, for speed */
void
do_print_rec(int nargs, int redirtype)
{
FILE *fp = NULL;
NODE *f0;
struct redirect *rp = NULL;
int errflg = 0;
NODE *redir_exp = NULL;
assert(nargs == 0);
if (redirtype != 0) {
redir_exp = TOP();
rp = redirect(redir_exp, redirtype, & errflg, true);
if (rp != NULL) {
if ((rp->flag & RED_TWOWAY) != 0 && rp->output.fp == NULL) {
if (is_non_fatal_redirect(redir_exp->stptr, redir_exp->stlen)) {
update_ERRNO_int(EBADF);
return;
}
(void) close_rp(rp, CLOSE_ALL);
fatal(_("print: attempt to write to closed write end of two-way pipe"));
}
fp = rp->output.fp;
}
DEREF(redir_exp);
decr_sp();
} else
fp = output_fp;
if (errflg) {
update_ERRNO_int(errflg);
return;
}
if (fp == NULL)
return;
if (! field0_valid || do_lint) // lint check for field access in END
(void) get_field(0L, NULL);
f0 = fields_arr[0];
if (do_lint && (f0->flags & NULL_FIELD) != 0)
lintwarn(_("reference to uninitialized field `$%d'"), 0);
efwrite(f0->stptr, sizeof(char), f0->stlen, fp, "print", rp, false);
if (ORSlen > 0)
efwrite(ORS, sizeof(char), (size_t) ORSlen, fp, "print", rp, true);
if (rp != NULL && (rp->flag & RED_TWOWAY) != 0)
rp->output.gawk_fflush(rp->output.fp, rp->output.opaque);
}
/* is_wupper --- function version of iswupper for passing function pointers */
static int
is_wupper(wchar_t c)
{
return iswupper(c);
}
/* is_wlower --- function version of iswlower for passing function pointers */
static int
is_wlower(wchar_t c)
{
return iswlower(c);
}
/* to_wupper --- function version of towupper for passing function pointers */
static int
to_wlower(wchar_t c)
{
return towlower(c);
}
/* to_wlower --- function version of towlower for passing function pointers */
static int
to_wupper(wchar_t c)
{
return towupper(c);
}
/* wide_change_case --- generic case converter for wide characters */
static void
wide_change_case(wchar_t *wstr,
size_t wlen,
int (*is_x)(wchar_t c),
int (*to_y)(wchar_t c))
{
size_t i;
wchar_t *wcp;
for (i = 0, wcp = wstr; i < wlen; i++, wcp++)
if (is_x(*wcp))
*wcp = to_y(*wcp);
}
/* wide_toupper --- map a wide string to upper case */
static void
wide_toupper(wchar_t *wstr, size_t wlen)
{
wide_change_case(wstr, wlen, is_wlower, to_wupper);
}
/* wide_tolower --- map a wide string to lower case */
static void
wide_tolower(wchar_t *wstr, size_t wlen)
{
wide_change_case(wstr, wlen, is_wupper, to_wlower);
}
/* do_tolower --- lower case a string */
NODE *
do_tolower(int nargs)
{
NODE *t1, *t2;
t1 = POP_SCALAR();
if (do_lint && (fixtype(t1)->flags & STRING) == 0)
lintwarn(_("tolower: received non-string argument"));
t1 = force_string(t1);
t2 = make_string(t1->stptr, t1->stlen);
if (gawk_mb_cur_max == 1) {
unsigned char *cp, *cp2;
for (cp = (unsigned char *)t2->stptr,
cp2 = (unsigned char *)(t2->stptr + t2->stlen);
cp < cp2; cp++)
if (isupper(*cp))
*cp = tolower(*cp);
} else {
force_wstring(t2);
wide_tolower(t2->wstptr, t2->wstlen);
wstr2str(t2);
}
DEREF(t1);
return t2;
}
/* do_toupper --- upper case a string */
NODE *
do_toupper(int nargs)
{
NODE *t1, *t2;
t1 = POP_SCALAR();
if (do_lint && (fixtype(t1)->flags & STRING) == 0)
lintwarn(_("toupper: received non-string argument"));
t1 = force_string(t1);
t2 = make_string(t1->stptr, t1->stlen);
if (gawk_mb_cur_max == 1) {
unsigned char *cp, *cp2;
for (cp = (unsigned char *)t2->stptr,
cp2 = (unsigned char *)(t2->stptr + t2->stlen);
cp < cp2; cp++)
if (islower(*cp))
*cp = toupper(*cp);
} else {
force_wstring(t2);
wide_toupper(t2->wstptr, t2->wstlen);
wstr2str(t2);
}
DEREF(t1);
return t2;
}
/* do_atan2 --- do the atan2 function */
NODE *
do_atan2(int nargs)
{
NODE *t1, *t2;
double d1, d2;
POP_TWO_SCALARS(t1, t2);
if (do_lint) {
if ((fixtype(t1)->flags & NUMBER) == 0)
lintwarn(_("atan2: received non-numeric first argument"));
if ((fixtype(t2)->flags & NUMBER) == 0)
lintwarn(_("atan2: received non-numeric second argument"));
}
d1 = force_number(t1)->numbr;
d2 = force_number(t2)->numbr;
DEREF(t1);
DEREF(t2);
return make_number((AWKNUM) atan2(d1, d2));
}
/* do_sin --- do the sin function */
NODE *
do_sin(int nargs)
{
NODE *tmp;
double d;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("sin: received non-numeric argument"));
d = sin((double) force_number(tmp)->numbr);
DEREF(tmp);
return make_number((AWKNUM) d);
}
/* do_cos --- do the cos function */
NODE *
do_cos(int nargs)
{
NODE *tmp;
double d;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("cos: received non-numeric argument"));
d = cos((double) force_number(tmp)->numbr);
DEREF(tmp);
return make_number((AWKNUM) d);
}
/* do_rand --- do the rand function */
static bool firstrand = true;
/* Some systems require this array to be integer aligned. Sigh. */
#define SIZEOF_STATE 256
static uint32_t istate[SIZEOF_STATE/sizeof(uint32_t)];
static char *const state = (char *const) istate;
/* ARGSUSED */
NODE *
do_rand(int nargs ATTRIBUTE_UNUSED)
{
double tmprand;
#define RAND_DIVISOR ((double)GAWK_RANDOM_MAX+1.0)
if (firstrand) {
(void) initstate((unsigned) 1, state, SIZEOF_STATE);
/* don't need to srandom(1), initstate() does it for us. */
firstrand = false;
setstate(state);
}
/*
* Per historical practice and POSIX, return value N is
*
* 0 <= n < 1
*/
/*
* Date: Wed, 28 Aug 2013 17:52:46 -0700
* From: Bob Jewett <jewett@bill.scs.agilent.com>
*
* Call random() twice to fill in more bits in the value
* of the double. Also, there is a bug in random() such
* that when the values of successive values are combined
* like (rand1*rand2)^2, (rand3*rand4)^2, ... the
* resulting time series is not white noise. The
* following also seems to fix that bug.
*
* The add/subtract 0.5 keeps small bits from filling
* below 2^-53 in the double, not that anyone should be
* looking down there.
*
* Date: Wed, 25 Sep 2013 10:45:38 -0600 (MDT)
* From: "Nelson H. F. Beebe" <beebe@math.utah.edu>
* (4) The code is typical of many published fragments for converting
* from integer to floating-point, and I discuss the serious pitfalls
* in my book, because it leads to platform-dependent behavior at the
* end points of the interval [0,1]
*
* (5) the documentation in the gawk info node says
*
* `rand()'
* Return a random number. The values of `rand()' are uniformly
* distributed between zero and one. The value could be zero but is
* never one.(1)
*
* The division by RAND_DIVISOR may not guarantee that 1.0 is never
* returned: the programmer forgot the platform-dependent issue of
* rounding.
*
* For points 4 and 5, the safe way is a loop:
*
* double
* rand(void) // return value in [0.0, 1.0)
* {
* value = internal_rand();
*
* while (value == 1.0)
* value = internal_rand();
*
* return (value);
* }
*/
do {
long d1, d2;
/*
* Do the calls in predictable order to avoid
* compiler differences in order of evaluation.
*/
d1 = random();
d2 = random();
tmprand = 0.5 + ( (d1/RAND_DIVISOR + d2) / RAND_DIVISOR );
tmprand -= 0.5;
} while (tmprand == 1.0);
return make_number((AWKNUM) tmprand);
}
/* do_srand --- seed the random number generator */
NODE *
do_srand(int nargs)
{
NODE *tmp;
static long save_seed = 1;
long ret = save_seed; /* SVR4 awk srand returns previous seed */
if (firstrand) {
(void) initstate((unsigned) 1, state, SIZEOF_STATE);
/* don't need to srandom(1), we're changing the seed below */
firstrand = false;
(void) setstate(state);
}
if (nargs == 0)
srandom((unsigned int) (save_seed = (long) time((time_t *) 0)));
else {
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("srand: received non-numeric argument"));
srandom((unsigned int) (save_seed = (long) force_number(tmp)->numbr));
DEREF(tmp);
}
return make_number((AWKNUM) ret);
}
/* do_match --- match a regexp, set RSTART and RLENGTH,
* optional third arg is array filled with text of
* subpatterns enclosed in parens and start and len info.
*/
NODE *
do_match(int nargs)
{
NODE *tre, *t1, *dest, *it;
int rstart, len, ii;
int rlength;
Regexp *rp;
regoff_t s;
char *start;
char *buf = NULL;
char buff[100];
size_t amt, oldamt = 0, ilen, slen;
char *subsepstr;
size_t subseplen;
dest = NULL;
if (nargs == 3) { /* 3rd optional arg for the subpatterns */
dest = POP_PARAM();
if (dest->type != Node_var_array)
fatal(_("match: third argument is not an array"));
assoc_clear(dest);
}
tre = POP();
rp = re_update(tre);
t1 = POP_STRING();
rstart = research(rp, t1->stptr, 0, t1->stlen, RE_NEED_START);
if (rstart >= 0) { /* match succeded */
size_t *wc_indices = NULL;
rlength = REEND(rp, t1->stptr) - RESTART(rp, t1->stptr); /* byte length */
if (rlength > 0 && gawk_mb_cur_max > 1) {
t1 = str2wstr(t1, & wc_indices);
rlength = wc_indices[rstart + rlength - 1] - wc_indices[rstart] + 1;
rstart = wc_indices[rstart];
}
rstart++; /* now it's 1-based indexing */
/* Build the array only if the caller wants the optional subpatterns */
if (dest != NULL) {
subsepstr = SUBSEP_node->var_value->stptr;
subseplen = SUBSEP_node->var_value->stlen;
for (ii = 0; ii < NUMSUBPATS(rp, t1->stptr); ii++) {
/*
* Loop over all the subpats; some of them may have
* matched even if all of them did not.
*/
if ((s = SUBPATSTART(rp, t1->stptr, ii)) != -1) {
size_t subpat_start;
size_t subpat_len;
start = t1->stptr + s;
subpat_start = s;
subpat_len = len = SUBPATEND(rp, t1->stptr, ii) - s;
if (len > 0 && gawk_mb_cur_max > 1) {
subpat_start = wc_indices[s];
subpat_len = wc_indices[s + len - 1] - subpat_start + 1;
}
it = make_string(start, len);
it->flags |= USER_INPUT;
assoc_set(dest, make_number((AWKNUM) (ii)), it);;
sprintf(buff, "%d", ii);
ilen = strlen(buff);
amt = ilen + subseplen + strlen("length") + 1;
if (oldamt == 0) {
emalloc(buf, char *, amt, "do_match");
} else if (amt > oldamt) {
erealloc(buf, char *, amt, "do_match");
}
oldamt = amt;
memcpy(buf, buff, ilen);
memcpy(buf + ilen, subsepstr, subseplen);
memcpy(buf + ilen + subseplen, "start", 6);
slen = ilen + subseplen + 5;
assoc_set(dest, make_string(buf, slen), make_number((AWKNUM) subpat_start + 1));
memcpy(buf, buff, ilen);
memcpy(buf + ilen, subsepstr, subseplen);
memcpy(buf + ilen + subseplen, "length", 7);
slen = ilen + subseplen + 6;
assoc_set(dest, make_string(buf, slen), make_number((AWKNUM) subpat_len));
}
}
efree(buf);
}
if (wc_indices != NULL)
efree(wc_indices);
} else { /* match failed */
rstart = 0;
rlength = -1;
}
DEREF(t1);
unref(RSTART_node->var_value);
RSTART_node->var_value = make_number((AWKNUM) rstart);
unref(RLENGTH_node->var_value);
RLENGTH_node->var_value = make_number((AWKNUM) rlength);
return make_number((AWKNUM) rstart);
}
/* do_sub --- do the work for sub, gsub, and gensub */
/*
* Gsub can be tricksy; particularly when handling the case of null strings.
* The following awk code was useful in debugging problems. It is too bad
* that it does not readily translate directly into the C code, below.
*
* #! /usr/local/bin/mawk -f
*
* BEGIN {
* true = 1; false = 0
* print "--->", mygsub("abc", "b+", "FOO")
* print "--->", mygsub("abc", "x*", "X")
* print "--->", mygsub("abc", "b*", "X")
* print "--->", mygsub("abc", "c", "X")
* print "--->", mygsub("abc", "c+", "X")
* print "--->", mygsub("abc", "x*$", "X")
* }
*
* function mygsub(str, regex, replace, origstr, newstr, eosflag, nonzeroflag)
* {
* origstr = str;
* eosflag = nonzeroflag = false
* while (match(str, regex)) {
* if (RLENGTH > 0) { # easy case
* nonzeroflag = true
* if (RSTART == 1) { # match at front of string
* newstr = newstr replace
* } else {
* newstr = newstr substr(str, 1, RSTART-1) replace
* }
* str = substr(str, RSTART+RLENGTH)
* } else if (nonzeroflag) {
* # last match was non-zero in length, and at the
* # current character, we get a zero length match,
* # which we don't really want, so skip over it
* newstr = newstr substr(str, 1, 1)
* str = substr(str, 2)
* nonzeroflag = false
* } else {
* # 0-length match
* if (RSTART == 1) {
* newstr = newstr replace substr(str, 1, 1)
* str = substr(str, 2)
* } else {
* return newstr str replace
* }
* }
* if (length(str) == 0)
* if (eosflag)
* break
* else
* eosflag = true
* }
* if (length(str) > 0)
* newstr = newstr str # rest of string
*
* return newstr
* }
*/
/*
* 1/2004: The gawk sub/gsub behavior dates from 1996, when we proposed it
* for POSIX. The proposal fell through the cracks, and the 2001 POSIX
* standard chose a more simple behavior.
*
* The relevant text is to be found on lines 6394-6407 (pages 166, 167) of the
* 2001 standard:
*
* sub(ere, repl[, in ])
* Substitute the string repl in place of the first instance of the
* extended regular expression ERE in string in and return the number of
* substitutions. An ampersand ('&') appearing in the string repl shall
* be replaced by the string from in that matches the ERE. An ampersand
* preceded with a backslash ('\') shall be interpreted as the literal
* ampersand character. An occurrence of two consecutive backslashes shall
* be interpreted as just a single literal backslash character. Any other
* occurrence of a backslash (for example, preceding any other character)
* shall be treated as a literal backslash character. Note that if repl is a
* string literal (the lexical token STRING; see Grammar (on page 170)), the
* handling of the ampersand character occurs after any lexical processing,
* including any lexical backslash escape sequence processing. If in is
* specified and it is not an lvalue (see Expressions in awk (on page 156)),
* the behavior is undefined. If in is omitted, awk shall use the current
* record ($0) in its place.
*
* 11/2010: The text in the 2008 standard is the same as just quoted.
* However, POSIX behavior is now the default. This can change the behavior
* of awk programs. The old behavior is not available.
*
* 7/2011: Reverted backslash handling to what it used to be. It was in
* gawk for too long. Should have known better.
*/
/*
* NB: `howmany' conflicts with a SunOS 4.x macro in <sys/param.h>.
*/
NODE *
do_sub(int nargs, unsigned int flags)
{
char *scan;
char *bp, *cp;
char *buf = NULL;
size_t buflen;
char *matchend;
size_t len;
char *matchstart;
char *text;
size_t textlen = 0;
char *repl;
char *replend;
size_t repllen;
int sofar;
int ampersands;
int matches = 0;
Regexp *rp;
NODE *rep_node; /* replacement text */
NODE *target; /* string to make sub. in; $0 if none given */
NODE *tmp;
NODE **lhs = NULL;
long how_many = 1; /* one substitution for sub, also gensub default */
bool global;
long current;
bool lastmatchnonzero;
char *mb_indices = NULL;
if ((flags & GENSUB) != 0) {
double d;
NODE *glob_flag;
tmp = PEEK(3);
rp = re_update(tmp);
target = POP_STRING(); /* original string */
glob_flag = POP_SCALAR(); /* value of global flag */
if ( (glob_flag->flags & STRING) != 0
&& glob_flag->stlen > 0
&& (glob_flag->stptr[0] == 'g' || glob_flag->stptr[0] == 'G'))
how_many = -1;
else {
(void) force_number(glob_flag);
d = get_number_d(glob_flag);
if (d < 1)
how_many = 1;
else if (d < LONG_MAX)
how_many = d;
else
how_many = LONG_MAX;
if (d <= 0) {
(void) force_string(glob_flag);
warning(_("gensub: third argument `%.*s' treated as 1"),
(int) glob_flag->stlen,
glob_flag->stptr);
}
}
DEREF(glob_flag);
} else {
/* take care of regexp early, in case re_update is fatal */
tmp = PEEK(2);
rp = re_update(tmp);
if ((flags & GSUB) != 0)
how_many = -1;
/* original string */
if ((flags & LITERAL) != 0)
target = POP_STRING();
else {
lhs = POP_ADDRESS();
target = force_string(*lhs);
}
}
global = (how_many == -1);
rep_node = POP_STRING(); /* replacement text */
decr_sp(); /* regexp, already updated above */
/* do the search early to avoid work on non-match */
if (research(rp, target->stptr, 0, target->stlen, RE_NEED_START) == -1 ||
RESTART(rp, target->stptr) > target->stlen)
goto done;
target->flags |= STRING;
text = target->stptr;
textlen = target->stlen;
repl = rep_node->stptr;
replend = repl + rep_node->stlen;
repllen = replend - repl;
ampersands = 0;
/*
* Some systems' malloc() can't handle being called with an
* argument of zero. Thus we have to have some special case
* code to check for `repllen == 0'. This can occur for
* something like:
* sub(/foo/, "", mystring)
* for example.
*/
if (gawk_mb_cur_max > 1 && repllen > 0) {
emalloc(mb_indices, char *, repllen * sizeof(char), "do_sub");
index_multibyte_buffer(repl, mb_indices, repllen);
}
/* compute length of replacement string, number of ampersands */
for (scan = repl; scan < replend; scan++) {
if ((gawk_mb_cur_max == 1 || (repllen > 0 && mb_indices[scan - repl] == 1))
&& (*scan == '&')) {
repllen--;
ampersands++;
} else if (*scan == '\\') {
if ((flags & GENSUB) != 0) { /* gensub, behave sanely */
if (isdigit((unsigned char) scan[1])) {
ampersands++;
scan++;
} else { /* \q for any q --> q */
repllen--;
scan++;
}
} else if (do_posix) {
/* \& --> &, \\ --> \ */
if (scan[1] == '&' || scan[1] == '\\') {
repllen--;
scan++;
} /* else
leave alone, it goes into the output */
} else {
/* gawk default behavior since 1996 */
if (strncmp(scan, "\\\\\\&", 4) == 0
|| strncmp(scan, "\\\\\\\\", 4) == 0) { /* 2016: fixed */
/* \\\& --> \& */
/* \\\\ --> \\ */
repllen -= 2;
scan += 3;
} else if (strncmp(scan, "\\\\&", 3) == 0) {
/* \\& --> \<string> */
ampersands++;
repllen--;
scan += 2;
} else if (scan[1] == '&') {
/* \& --> & */
repllen--;
scan++;
} /* else
leave alone, it goes into the output */
}
}
}
lastmatchnonzero = false;
/* guesstimate how much room to allocate; +1 forces > 0 */
buflen = textlen + (ampersands + 1) * repllen + 1;
emalloc(buf, char *, buflen + 1, "do_sub");
buf[buflen] = '\0';
bp = buf;
for (current = 1;; current++) {
matches++;
matchstart = target->stptr + RESTART(rp, target->stptr);
matchend = target->stptr + REEND(rp, target->stptr);
/*
* create the result, copying in parts of the original
* string. note that length of replacement string can
* vary since ampersand is actual text of regexp match.
*/
/*
* add 1 to len to handle "empty" case where
* matchend == matchstart and we force a match on a single
* char. Use 'matchend - text' instead of 'matchstart - text'
* because we may not actually make any substitution depending
* on the 'global' and 'how_many' values.
*/
len = matchend - text + repllen
+ ampersands * (matchend - matchstart) + 1;
sofar = bp - buf;
while (buflen < (sofar + len + 1)) {
buflen *= 2;
erealloc(buf, char *, buflen, "sub_common");
bp = buf + sofar;
}
for (scan = text; scan < matchstart; scan++)
*bp++ = *scan;
if (global || current == how_many) {
/*
* If the current match matched the null string,
* and the last match didn't and did a replacement,
* and the match of the null string is at the front of
* the text (meaning right after end of the previous
* replacement), then skip this one.
*/
if (matchstart == matchend
&& lastmatchnonzero
&& matchstart == text) {
lastmatchnonzero = false;
matches--;
goto empty;
}
/*
* If replacing all occurrences, or this is the
* match we want, copy in the replacement text,
* making substitutions as we go.
*/
for (scan = repl; scan < replend; scan++)
if (*scan == '&'
/*
* Don't test repllen here. A simple "&" could
* end up with repllen == 0.
*/
&& (gawk_mb_cur_max == 1
|| mb_indices[scan - repl] == 1)
) {
for (cp = matchstart; cp < matchend; cp++)
*bp++ = *cp;
} else if (*scan == '\\'
&& (gawk_mb_cur_max == 1
|| (repllen > 0 && mb_indices[scan - repl] == 1))
) {
if (flags & GENSUB) { /* gensub, behave sanely */
if (isdigit((unsigned char) scan[1])) {
int dig = scan[1] - '0';
if (dig < NUMSUBPATS(rp, target->stptr) && SUBPATSTART(rp, tp->stptr, dig) != -1) {
char *start, *end;
start = target->stptr
+ SUBPATSTART(rp, target->stptr, dig);
end = target->stptr
+ SUBPATEND(rp, target->stptr, dig);
for (cp = start; cp < end; cp++)
*bp++ = *cp;
}
scan++;
} else /* \q for any q --> q */
*bp++ = *++scan;
} else if (do_posix) {
/* \& --> &, \\ --> \ */
if (scan[1] == '&' || scan[1] == '\\')
scan++;
*bp++ = *scan;
} else {
/* gawk default behavior since 1996 */
if (strncmp(scan, "\\\\\\&", 4) == 0
|| strncmp(scan, "\\\\\\\\", 4) == 0) { /* 2016: fixed */
/* \\\& --> \& */
/* \\\\ --> \\ */
*bp++ = '\\';
*bp++ = scan[3];
scan += 3;
} else if (strncmp(scan, "\\\\&", 3) == 0) {
/* \\& --> \<string> */
*bp++ = '\\';
for (cp = matchstart; cp < matchend; cp++)
*bp++ = *cp;
scan += 2;
} else if (scan[1] == '&') {
/* \& --> & */
*bp++ = '&';
scan++;
} else
*bp++ = *scan;
}
} else
*bp++ = *scan;
if (matchstart != matchend)
lastmatchnonzero = true;
} else {
/*
* don't want this match, skip over it by copying
* in current text.
*/
for (cp = matchstart; cp < matchend; cp++)
*bp++ = *cp;
}
empty:
/* catch the case of gsub(//, "blah", whatever), i.e. empty regexp */
if (matchstart == matchend && matchend < text + textlen) {
*bp++ = *matchend;
matchend++;
}
textlen = text + textlen - matchend;
text = matchend;
#if 0
if (bp - buf > sofar + len)
fprintf(stderr, "debug: len = %zu, but used %ld\n", len, (long)((bp - buf) - (long)sofar));
#endif
if ((current >= how_many && ! global)
|| ((long) textlen <= 0 && matchstart == matchend)
|| research(rp, target->stptr, text - target->stptr, textlen, RE_NEED_START) == -1)
break;
}
sofar = bp - buf;
if (buflen < (sofar + textlen + 1)) {
buflen = sofar + textlen + 1;
erealloc(buf, char *, buflen, "do_sub");
bp = buf + sofar;
}
/*
* Note that text == matchend, since that assignment is made before
* exiting the 'for' loop above. Thus we copy in the rest of the
* original string.
*/
for (scan = text; scan < text + textlen; scan++)
*bp++ = *scan;
*bp = '\0';
textlen = bp - buf;
if (mb_indices != NULL)
efree(mb_indices);
done:
DEREF(rep_node);
if ((matches == 0 || (flags & LITERAL) != 0) && buf != NULL) {
efree(buf);
buf = NULL;
}
if (flags & GENSUB) {
if (matches > 0) {
/* return the result string */
DEREF(target);
assert(buf != NULL);
return make_str_node(buf, textlen, ALREADY_MALLOCED);
}
/* return the original string */
return target;
}
/* For a string literal, must not change the original string. */
if ((flags & LITERAL) != 0)
DEREF(target);
else if (matches > 0) {
unref(*lhs);
*lhs = make_str_node(buf, textlen, ALREADY_MALLOCED);
}
return make_number((AWKNUM) matches);
}
/* call_sub --- call do_sub indirectly */
NODE *
call_sub(const char *name, int nargs)
{
unsigned int flags = 0;
NODE *regex, *replace, *glob_flag;
NODE **lhs, *rhs;
NODE *zero = make_number(0.0);
NODE *result;
if (name[0] == 'g') {
if (name[1] == 'e')
flags = GENSUB;
else
flags = GSUB;
}
if (flags == 0 || flags == GSUB) {
/* sub or gsub */
if (nargs != 2)
fatal(_("%s: can be called indirectly only with two arguments"), name);
replace = POP_STRING();
regex = POP(); /* the regex */
/*
* push regex
* push replace
* push $0
*/
if ((regex->flags & REGEX) != 0)
regex = regex->typed_re;
else
regex = make_regnode(Node_regex, regex);
PUSH(regex);
PUSH(replace);
lhs = r_get_field(zero, (Func_ptr *) 0, true);
nargs++;
PUSH_ADDRESS(lhs);
} else {
/* gensub */
if (nargs == 4)
rhs = POP();
else
rhs = NULL;
glob_flag = POP_STRING();
replace = POP_STRING();
regex = POP(); /* the regex */
/*
* push regex
* push replace
* push glob_flag
* if (nargs = 3) {
* push $0
* nargs++
* }
*/
if ((regex->flags & REGEX) != 0)
regex = regex->typed_re;
else
regex = make_regnode(Node_regex, regex);
PUSH(regex);
PUSH(replace);
PUSH(glob_flag);
if (rhs == NULL) {
lhs = r_get_field(zero, (Func_ptr *) 0, true);
rhs = *lhs;
UPREF(rhs);
PUSH(rhs);
nargs++;
}
else
PUSH(rhs);
}
unref(zero);
result = do_sub(nargs, flags);
if (flags != GENSUB)
reset_record();
return result;
}
/* call_match --- call do_match indirectly */
NODE *
call_match(int nargs)
{
NODE *regex, *text, *array;
NODE *result;
regex = text = array = NULL;
if (nargs == 3)
array = POP();
regex = POP();
/* Don't need to pop the string just to push it back ... */
if ((regex->flags & REGEX) != 0)
regex = regex->typed_re;
else
regex = make_regnode(Node_regex, regex);
PUSH(regex);
if (array)
PUSH(array);
result = do_match(nargs);
return result;
}
/* call_split_func --- call do_split or do_pat_split indirectly */
NODE *
call_split_func(const char *name, int nargs)
{
NODE *regex, *seps;
NODE *result;
regex = seps = NULL;
if (nargs < 2)
fatal(_("indirect call to %s requires at least two arguments"),
name);
if (nargs == 4)
seps = POP();
if (nargs >= 3) {
regex = POP_STRING();
if ((regex->flags & REGEX) != 0)
regex = regex->typed_re;
else
regex = make_regnode(Node_regex, regex);
} else {
if (name[0] == 's') {
regex = make_regnode(Node_regex, FS_node->var_value);
regex->re_flags |= FS_DFLT;
} else
regex = make_regnode(Node_regex, FPAT_node->var_value);
nargs++;
}
/* Don't need to pop the string or the data array */
PUSH(regex);
if (seps)
PUSH(seps);
result = (name[0] == 's') ? do_split(nargs) : do_patsplit(nargs);
return result;
}
/* make_integer - Convert an integer to a number node. */
static NODE *
make_integer(uintmax_t n)
{
n = adjust_uint(n);
return make_number((AWKNUM) n);
}
/* do_lshift --- perform a << operation */
NODE *
do_lshift(int nargs)
{
NODE *s1, *s2;
uintmax_t uval, ushift, res;
AWKNUM val, shift;
POP_TWO_SCALARS(s1, s2);
if (do_lint) {
if ((fixtype(s1)->flags & NUMBER) == 0)
lintwarn(_("lshift: received non-numeric first argument"));
if ((fixtype(s2)->flags & NUMBER) == 0)
lintwarn(_("lshift: received non-numeric second argument"));
}
val = force_number(s1)->numbr;
shift = force_number(s2)->numbr;
if (val < 0 || shift < 0)
fatal(_("lshift(%f, %f): negative values are not allowed"), val, shift);
if (do_lint) {
if (double_to_int(val) != val || double_to_int(shift) != shift)
lintwarn(_("lshift(%f, %f): fractional values will be truncated"), val, shift);
if (shift >= sizeof(uintmax_t) * CHAR_BIT)
lintwarn(_("lshift(%f, %f): too large shift value will give strange results"), val, shift);
}
DEREF(s1);
DEREF(s2);
uval = (uintmax_t) val;
ushift = (uintmax_t) shift;
res = uval << ushift;
return make_integer(res);
}
/* do_rshift --- perform a >> operation */
NODE *
do_rshift(int nargs)
{
NODE *s1, *s2;
uintmax_t uval, ushift, res;
AWKNUM val, shift;
POP_TWO_SCALARS(s1, s2);
if (do_lint) {
if ((fixtype(s1)->flags & NUMBER) == 0)
lintwarn(_("rshift: received non-numeric first argument"));
if ((fixtype(s2)->flags & NUMBER) == 0)
lintwarn(_("rshift: received non-numeric second argument"));
}
val = force_number(s1)->numbr;
shift = force_number(s2)->numbr;
if (val < 0 || shift < 0)
fatal(_("rshift(%f, %f): negative values are not allowed"), val, shift);
if (do_lint) {
if (double_to_int(val) != val || double_to_int(shift) != shift)
lintwarn(_("rshift(%f, %f): fractional values will be truncated"), val, shift);
if (shift >= sizeof(uintmax_t) * CHAR_BIT)
lintwarn(_("rshift(%f, %f): too large shift value will give strange results"), val, shift);
}
DEREF(s1);
DEREF(s2);
uval = (uintmax_t) val;
ushift = (uintmax_t) shift;
res = uval >> ushift;
return make_integer(res);
}
/* do_and --- perform an & operation */
NODE *
do_and(int nargs)
{
NODE *s1;
uintmax_t res, uval;
AWKNUM val;
res = ~(uintmax_t) 0; /* start off with all ones */
if (nargs < 2)
fatal(_("and: called with less than two arguments"));
for (; nargs > 0; nargs--) {
s1 = POP_SCALAR();
if (do_lint && (fixtype(s1)->flags & NUMBER) == 0)
lintwarn(_("and: argument %d is non-numeric"), nargs);
val = force_number(s1)->numbr;
if (val < 0)
fatal(_("and: argument %d negative value %g is not allowed"), nargs, val);
uval = (uintmax_t) val;
res &= uval;
DEREF(s1);
}
return make_integer(res);
}
/* do_or --- perform an | operation */
NODE *
do_or(int nargs)
{
NODE *s1;
uintmax_t res, uval;
AWKNUM val;
res = 0;
if (nargs < 2)
fatal(_("or: called with less than two arguments"));
for (; nargs > 0; nargs--) {
s1 = POP_SCALAR();
if (do_lint && (fixtype(s1)->flags & NUMBER) == 0)
lintwarn(_("or: argument %d is non-numeric"), nargs);
val = force_number(s1)->numbr;
if (val < 0)
fatal(_("or: argument %d negative value %g is not allowed"), nargs, val);
uval = (uintmax_t) val;
res |= uval;
DEREF(s1);
}
return make_integer(res);
}
/* do_xor --- perform an ^ operation */
NODE *
do_xor(int nargs)
{
NODE *s1;
uintmax_t res, uval;
AWKNUM val;
if (nargs < 2)
fatal(_("xor: called with less than two arguments"));
res = 0; /* start with all zeroes */
for (; nargs > 0; nargs--) {
s1 = POP_SCALAR();
if (do_lint && (fixtype(s1)->flags & NUMBER) == 0)
lintwarn(_("xor: argument %d is non-numeric"), nargs);
val = force_number(s1)->numbr;
if (val < 0)
fatal(_("xor: argument %d negative value %g is not allowed"), nargs, val);
uval = (uintmax_t) val;
res ^= uval;
DEREF(s1);
}
return make_integer(res);
}
/* do_compl --- perform a ~ operation */
NODE *
do_compl(int nargs)
{
NODE *tmp;
double d;
uintmax_t uval;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("compl: received non-numeric argument"));
d = force_number(tmp)->numbr;
DEREF(tmp);
if (d < 0)
fatal(_("compl(%f): negative value is not allowed"), d);
if (do_lint && double_to_int(d) != d)
lintwarn(_("compl(%f): fractional value will be truncated"), d);
uval = (uintmax_t) d;
uval = ~ uval;
return make_integer(uval);
}
/* do_strtonum --- the strtonum function */
NODE *
do_strtonum(int nargs)
{
NODE *tmp;
AWKNUM d;
tmp = fixtype(POP_SCALAR());
if ((tmp->flags & NUMBER) != 0)
d = (AWKNUM) tmp->numbr;
else if (get_numbase(tmp->stptr, tmp->stlen, use_lc_numeric) != 10)
d = nondec2awknum(tmp->stptr, tmp->stlen, NULL);
else
d = (AWKNUM) force_number(tmp)->numbr;
DEREF(tmp);
return make_number((AWKNUM) d);
}
/* nondec2awknum --- convert octal or hex value to double */
/*
* Because of awk's concatenation rules and the way awk.y:yylex()
* collects a number, this routine has to be willing to stop on the
* first invalid character.
*/
AWKNUM
nondec2awknum(char *str, size_t len, char **endptr)
{
AWKNUM retval = 0.0;
char save;
short val;
char *start = str;
if (len >= 2 && *str == '0' && (str[1] == 'x' || str[1] == 'X')) {
/*
* User called strtonum("0x") or some such,
* so just quit early.
*/
if (len <= 2) {
if (endptr)
*endptr = start;
return (AWKNUM) 0.0;
}
for (str += 2, len -= 2; len > 0; len--, str++) {
switch (*str) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
val = *str - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
val = *str - 'a' + 10;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
val = *str - 'A' + 10;
break;
default:
if (endptr)
*endptr = str;
goto done;
}
retval = (retval * 16) + val;
}
if (endptr)
*endptr = str;
} else if (len >= 1 && *str == '0') {
for (; len > 0; len--) {
if (! isdigit((unsigned char) *str)) {
if (endptr)
*endptr = str;
goto done;
}
else if (*str == '8' || *str == '9') {
str = start;
goto decimal;
}
retval = (retval * 8) + (*str - '0');
str++;
}
if (endptr)
*endptr = str;
} else {
decimal:
save = str[len];
str[len] = '\0';
retval = strtod(str, endptr);
str[len] = save;
}
done:
return retval;
}
/* do_dcgettext, do_dcngettext --- handle i18n translations */
#if ENABLE_NLS && defined(LC_MESSAGES) && HAVE_DCGETTEXT
static int
localecategory_from_argument(NODE *t)
{
static const struct category_table {
int val;
const char *name;
} cat_tab[] = {
#ifdef LC_ALL
{ LC_ALL, "LC_ALL" },
#endif /* LC_ALL */
#ifdef LC_COLLATE
{ LC_COLLATE, "LC_COLLATE" },
#endif /* LC_COLLATE */
#ifdef LC_CTYPE
{ LC_CTYPE, "LC_CTYPE" },
#endif /* LC_CTYPE */
#ifdef LC_MESSAGES
{ LC_MESSAGES, "LC_MESSAGES" },
#endif /* LC_MESSAGES */
#ifdef LC_MONETARY
{ LC_MONETARY, "LC_MONETARY" },
#endif /* LC_MONETARY */
#ifdef LC_NUMERIC
{ LC_NUMERIC, "LC_NUMERIC" },
#endif /* LC_NUMERIC */
#ifdef LC_RESPONSE
{ LC_RESPONSE, "LC_RESPONSE" },
#endif /* LC_RESPONSE */
#ifdef LC_TIME
{ LC_TIME, "LC_TIME" },
#endif /* LC_TIME */
};
if (t != NULL) {
int low, high, i, mid;
char *category;
int lc_cat = -1;
char save = t->stptr[t->stlen];
t->stptr[t->stlen] = '\0';
category = t->stptr;
/* binary search the table */
low = 0;
high = (sizeof(cat_tab) / sizeof(cat_tab[0])) - 1;
while (low <= high) {
mid = (low + high) / 2;
i = strcmp(category, cat_tab[mid].name);
if (i < 0) /* category < mid */
high = mid - 1;
else if (i > 0) /* category > mid */
low = mid + 1;
else {
lc_cat = cat_tab[mid].val;
break;
}
}
t->stptr[t->stlen] = save;
if (lc_cat == -1) /* not there */
fatal(_("dcgettext: `%s' is not a valid locale category"), category);
return lc_cat;
} else
return LC_MESSAGES;
}
#endif
/*
* awk usage is
*
* str = dcgettext(string [, domain [, category]])
* str = dcngettext(string1, string2, number [, domain [, category]])
*
* Default domain is TEXTDOMAIN, default category is LC_MESSAGES.
*/
NODE *
do_dcgettext(int nargs)
{
NODE *tmp, *t1, *t2 = NULL;
char *string;
char *the_result;
size_t reslen;
#if ENABLE_NLS && defined(LC_MESSAGES) && HAVE_DCGETTEXT
int lc_cat;
char *domain;
char save1 = '\0', save2 = '\0';
if (nargs == 3) { /* third argument */
tmp = POP_STRING();
lc_cat = localecategory_from_argument(tmp);
DEREF(tmp);
} else
lc_cat = LC_MESSAGES;
if (nargs >= 2) { /* second argument */
t2 = POP_STRING();
domain = t2->stptr;
str_terminate(t2, save2);
} else
domain = TEXTDOMAIN;
#else
if (nargs == 3) {
tmp = POP_STRING();
DEREF(tmp);
}
if (nargs >= 2) {
t2 = POP_STRING();
DEREF(t2);
}
#endif
t1 = POP_STRING(); /* first argument */
string = t1->stptr;
#if ENABLE_NLS && defined(LC_MESSAGES) && HAVE_DCGETTEXT
str_terminate(t1, save1);
the_result = dcgettext(domain, string, lc_cat);
str_restore(t1, save1);
if (t2 != NULL) {
str_restore(t2, save2);
DEREF(t2);
}
reslen = strlen(the_result);
#else
the_result = string;
reslen = t1->stlen;
#endif
DEREF(t1);
return make_string(the_result, reslen);
}
NODE *
do_dcngettext(int nargs)
{
NODE *tmp, *t1, *t2, *t3;
char *string1, *string2;
unsigned long number;
AWKNUM d;
char *the_result;
size_t reslen;
#if ENABLE_NLS && defined(LC_MESSAGES) && HAVE_DCGETTEXT
int lc_cat;
char *domain;
char save = '\0', save1 = '\0', save2 = '\0';
bool saved_end = false;
if (nargs == 5) { /* fifth argument */
tmp = POP_STRING();
lc_cat = localecategory_from_argument(tmp);
DEREF(tmp);
} else
lc_cat = LC_MESSAGES;
t3 = NULL;
if (nargs >= 4) { /* fourth argument */
t3 = POP_STRING();
domain = t3->stptr;
save = domain[t3->stlen];
domain[t3->stlen] = '\0';
saved_end = true;
} else
domain = TEXTDOMAIN;
#else
if (nargs == 5) {
tmp = POP_STRING();
DEREF(tmp);
}
if (nargs >= 4) {
t3 = POP_STRING();
DEREF(t3);
}
#endif
t2 = POP_NUMBER(); /* third argument */
d = get_number_d(t2);
DEREF(t2);
number = (unsigned long) double_to_int(d);
t2 = POP_STRING(); /* second argument */
string2 = t2->stptr;
t1 = POP_STRING(); /* first argument */
string1 = t1->stptr;
#if ENABLE_NLS && defined(LC_MESSAGES) && HAVE_DCGETTEXT
str_terminate(t1, save1);
str_terminate(t2, save2);
the_result = dcngettext(domain, string1, string2, number, lc_cat);
reslen = strlen(the_result);
str_restore(t1, save1);
str_restore(t2, save2);
if (saved_end)
domain[t3->stlen] = save;
if (t3 != NULL)
DEREF(t3);
#else
if (number == 1) {
the_result = string1;
reslen = t1->stlen;
} else {
the_result = string2;
reslen = t2->stlen;
}
#endif
DEREF(t1);
DEREF(t2);
return make_string(the_result, reslen);
}
/* do_bindtextdomain --- set the directory for a text domain */
/*
* awk usage is
*
* binding = bindtextdomain(dir [, domain])
*
* If dir is "", pass NULL to C version.
* Default domain is TEXTDOMAIN.
*/
NODE *
do_bindtextdomain(int nargs)
{
NODE *t1, *t2;
const char *directory, *domain;
const char *the_result;
t1 = t2 = NULL;
/* set defaults */
directory = NULL;
domain = TEXTDOMAIN;
char save = '\0', save1 = '\0';
if (nargs == 2) { /* second argument */
t2 = POP_STRING();
domain = (const char *) t2->stptr;
save = t2->stptr[t2->stlen];
t2->stptr[t2->stlen] = '\0';
}
/* first argument */
t1 = POP_STRING();
if (t1->stlen > 0) {
directory = (const char *) t1->stptr;
str_terminate(t1, save1);
}
the_result = bindtextdomain(domain, directory);
if (directory)
str_restore(t1, save1);
DEREF(t1);
if (t2 != NULL) {
t2->stptr[t2->stlen] = save;
DEREF(t2);
}
return make_string(the_result, strlen(the_result));
}
#ifdef SUPPLY_INTDIV
/* do_intdiv --- do integer division, return quotient and remainder in dest array */
/*
* We define the semantics as:
* numerator = int(numerator)
* denominator = int(denonmator)
* quotient = int(numerator / denomator)
* remainder = int(numerator % denomator)
*/
NODE *
do_intdiv(int nargs)
{
NODE *numerator, *denominator, *result;
double num, denom, quotient, remainder;
result = POP_PARAM();
if (result->type != Node_var_array)
fatal(_("intdiv: third argument is not an array"));
assoc_clear(result);
denominator = POP_SCALAR();
numerator = POP_SCALAR();
if (do_lint) {
if ((fixtype(numerator)->flags & NUMBER) == 0)
lintwarn(_("intdiv: received non-numeric first argument"));
if ((fixtype(denominator)->flags & NUMBER) == 0)
lintwarn(_("intdiv: received non-numeric second argument"));
}
(void) force_number(numerator);
(void) force_number(denominator);
num = double_to_int(get_number_d(numerator));
denom = double_to_int(get_number_d(denominator));
if (denom == 0.0)
fatal(_("intdiv: division by zero attempted"));
quotient = double_to_int(num / denom);
/*
* FIXME: This code is duplicated, factor it out to a
* separate function.
*/
#ifdef HAVE_FMOD
remainder = fmod(num, denom);
#else /* ! HAVE_FMOD */
(void) modf(num / denom, & remainder);
remainder = num - remainder * denom;
#endif /* ! HAVE_FMOD */
remainder = double_to_int(remainder);
assoc_set(result, make_string("quotient", 8), make_number((AWKNUM) quotient));
assoc_set(result, make_string("remainder", 9), make_number((AWKNUM) remainder));
DEREF(denominator);
DEREF(numerator);
return make_number((AWKNUM) 0.0);
}
#endif /* SUPPLY_INTDIV */
/* do_typeof --- return a string with the type of the arg */
NODE *
do_typeof(int nargs)
{
NODE *arg;
char *res = NULL;
bool deref = true;
NODE *dbg;
if (nargs == 2) { /* 2nd optional arg for debugging */
dbg = POP_PARAM();
if (dbg->type != Node_var_array)
fatal(_("typeof: second argument is not an array"));
assoc_clear(dbg);
}
else
dbg = NULL;
arg = POP();
switch (arg->type) {
case Node_var_array:
/* Node_var_array is never UPREF'ed */
res = "array";
deref = false;
if (dbg) {
assoc_set(dbg, make_string("array_type", 10), make_string(arg->array_funcs->name, strlen(arg->array_funcs->name)));
if (arg == PROCINFO_node) {
int i;
for (i = 0; i < BLOCK_MAX; i++) {
char *p;
size_t nl = strlen(nextfree[i].name);
/*
* save values before we create new
* array elements so that we have a
* snapshot at a consistent moment in
* time
*/
long hw = nextfree[i].highwater;
long active;
#ifdef MEMDEBUG
active = nextfree[i].active;
#else
active = hw;
{
struct block_item *ip;
for (ip = nextfree[i].freep; ip; ip = ip->freep)
active--;
}
#endif
#define SETVAL(X, V) { \
size_t l = nl + sizeof(#X); \
emalloc(p, char *, l+1, "do_typeof"); \
sprintf(p, "%s_" #X, nextfree[i].name); \
assoc_set(dbg, make_str_node(p, l, ALREADY_MALLOCED), make_number((AWKNUM) (V))); \
}
SETVAL(highwater, hw)
SETVAL(active, active)
#undef SETVAL
}
}
}
break;
case Node_val:
switch (fixtype(arg)->flags & (STRING|NUMBER|USER_INPUT|REGEX)) {
case NUMBER:
res = "number";
break;
case NUMBER|USER_INPUT:
res = "strnum";
break;
case REGEX:
res = "regexp";
break;
case STRING:
res = "string";
// fall through
case NUMBER|STRING:
if (arg == Nnull_string || (arg->flags & NULL_FIELD) != 0) {
res = "unassigned";
break;
}
/* fall through */
default:
if (res == NULL) {
warning(_("typeof detected invalid flags combination `%s'; please file a bug report."), flags2str(arg->flags));
res = "unknown";
}
break;
}
if (dbg) {
const char *s = flags2str(arg->flags);
assoc_set(dbg, make_string("flags", 5), make_string(s, strlen(s)));
}
break;
case Node_var_new:
res = "untyped";
deref = false;
break;
case Node_var:
/*
* Note: this doesn't happen because the function calling code
* in interpret.h pushes Node_var->var_value.
*/
fatal(_("typeof: invalid argument type `%s'"),
nodetype2str(arg->type));
break;
default:
fatal(_("typeof: unknown argument type `%s'"),
nodetype2str(arg->type));
break;
}
if (deref)
DEREF(arg);
return make_string(res, strlen(res));
}
/* mbc_byte_count --- return number of bytes for corresponding numchars multibyte characters */
static size_t
mbc_byte_count(const char *ptr, size_t numchars)
{
mbstate_t cur_state;
size_t sum = 0;
int mb_len;
memset(& cur_state, 0, sizeof(cur_state));
assert(gawk_mb_cur_max > 1);
mb_len = mbrlen(ptr, numchars * gawk_mb_cur_max, &cur_state);
if (mb_len <= 0)
return numchars; /* no valid m.b. char */
for (; numchars > 0; numchars--) {
mb_len = mbrlen(ptr, numchars * gawk_mb_cur_max, &cur_state);
if (mb_len <= 0)
break;
sum += mb_len;
ptr += mb_len;
}
return sum;
}
/* mbc_char_count --- return number of m.b. chars in string, up to numbytes bytes */
static size_t
mbc_char_count(const char *ptr, size_t numbytes)
{
mbstate_t cur_state;
size_t sum = 0;
int mb_len;
if (gawk_mb_cur_max == 1)
return numbytes;
memset(& cur_state, 0, sizeof(cur_state));
mb_len = mbrlen(ptr, numbytes, &cur_state);
if (mb_len <= 0)
return numbytes; /* no valid m.b. char */
while (numbytes > 0) {
mb_len = mbrlen(ptr, numbytes, &cur_state);
if (mb_len <= 0)
break;
sum++;
ptr += mb_len;
numbytes -= mb_len;
}
return sum;
}
/* sanitize_exit_status --- convert a 16 bit Unix exit status into something reasonable */
int sanitize_exit_status(int status)
{
int ret = 0;
if (WIFEXITED(status))
ret = WEXITSTATUS(status); /* normal exit */
else if (WIFSIGNALED(status)) {
bool coredumped = false;
#ifdef WCOREDUMP
coredumped = WCOREDUMP(status);
#endif
/* use 256 since exit values are 8 bits */
ret = WTERMSIG(status) + (coredumped ? 512 : 256);
} else
ret = 0; /* shouldn't get here */
return ret;
}
/* out_of_range --- return true if a value is out of range */
bool
out_of_range(NODE *n)
{
#ifdef HAVE_MPFR
if (is_mpg_integer(n))
return false;
else if (is_mpg_float(n))
return (! mpfr_number_p(n->mpg_numbr));
else
#endif
return (isnan(n->numbr) || isinf(n->numbr));
}
/* format_nan_inf --- format NaN and INF values */
char *
format_nan_inf(NODE *n, char format)
{
static char buf[100];
#ifdef HAVE_MPFR
if (is_mpg_integer(n))
return NULL;
else if (is_mpg_float(n)) {
if (mpfr_nan_p(n->mpg_numbr)) {
strcpy(buf, mpfr_sgn(n->mpg_numbr) < 0 ? "-nan" : "+nan");
goto fmt;
} else if (mpfr_inf_p(n->mpg_numbr)) {
strcpy(buf, mpfr_sgn(n->mpg_numbr) < 0 ? "-inf" : "+inf");
goto fmt;
} else
return NULL;
}
/* else
fallthrough */
#endif
double val = n->numbr;
if (isnan(val)) {
strcpy(buf, signbit(val) != 0 ? "-nan" : "+nan");
// fall through to end
} else if (isinf(val)) {
strcpy(buf, val < 0 ? "-inf" : "+inf");
// fall through to end
} else
return NULL;
#ifdef HAVE_MPFR
fmt:
#endif
if (isupper(format)) {
int i;
for (i = 0; buf[i] != '\0'; i++)
buf[i] = toupper(buf[i]);
}
return buf;
}
|