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
|
/*
* This file is part of libfaketime, version 0.9.9
*
* libfaketime is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License v2 as published by the
* Free Software Foundation.
*
* libfaketime 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 v2 along
* with the libfaketime; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* =======================================================================
* Global settings, includes, and macros === HEAD
* =======================================================================
*/
#define _GNU_SOURCE /* required to get RTLD_NEXT defined */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#ifdef __linux__
#include <sys/epoll.h>
#endif
#include <time.h>
#ifdef MACOS_DYLD_INTERPOSE
#include <sys/time.h>
#endif
#include <math.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <limits.h>
#ifdef INTERCEPT_SYSCALL
#ifdef __linux__
#include <stdarg.h>
#include <sys/syscall.h>
#else
#error INTERCEPT_SYSCALL should only be defined on GNU/Linux systems.
#endif
#endif
#ifdef __linux__
#include <sys/timerfd.h>
#endif
#include "uthash.h"
#include "time_ops.h"
#include "faketime_common.h"
#if defined PTHREAD_SINGLETHREADED_TIME && defined FAKE_STATELESS
#undef PTHREAD_SINGLETHREADED_TIME
#endif
/* pthread-handling contributed by David North, TDI in version 0.7 */
#if defined PTHREAD_SINGLETHREADED_TIME || defined FAKE_PTHREAD
#include <pthread.h>
#include <signal.h>
#endif
#include <sys/timeb.h>
#include <dlfcn.h>
#define BUFFERLEN 256
#ifndef __APPLE__
extern char *__progname;
#ifdef __sun
#include "sunos_endian.h"
#else
#include <endian.h>
#endif
#else
/* endianness related macros */
#ifndef OSSwapHostToBigInt64
#define OSSwapHostToBigInt64(x) ((uint64_t)(x))
#endif
#define htobe64(x) OSSwapHostToBigInt64(x)
#ifndef OSSwapHostToLittleInt64
#define OSSwapHostToLittleInt64(x) OSSwapInt64(x)
#endif
#define htole64(x) OSSwapHostToLittleInt64(x)
#ifndef OSSwapBigToHostInt64
#define OSSwapBigToHostInt64(x) ((uint64_t)(x))
#endif
#define be64toh(x) OSSwapBigToHostInt64(x)
#ifndef OSSwapLittleToHostInt64
#define OSSwapLittleToHostInt64(x) OSSwapInt64(x)
#endif
#define le64toh(x) OSSwapLittleToHostInt64(x)
/* clock_gettime() and related clock definitions are missing on __APPLE__ */
#ifndef CLOCK_REALTIME
/* from GNU C Library time.h */
/* Identifier for system-wide realtime clock. ( == 1) */
#define CLOCK_REALTIME CALENDAR_CLOCK
/* Monotonic system-wide clock. (== 0) */
#define CLOCK_MONOTONIC SYSTEM_CLOCK
/* High-resolution timer from the CPU. */
#define CLOCK_PROCESS_CPUTIME_ID 2
/* Thread-specific CPU-time clock. */
#define CLOCK_THREAD_CPUTIME_ID 3
/* Monotonic system-wide clock, not adjusted for frequency scaling. */
#define CLOCK_MONOTONIC_RAW 4
typedef int clockid_t;
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#ifdef MACOS_DYLD_INTERPOSE
void do_macos_dyld_interpose(void);
#define DYLD_INTERPOSE(_new,_target) \
__attribute__((used)) static struct{ const void* new; const void* target; } _interpose_##_target \
__attribute__ ((section ("__DATA,__interpose"))) = { (const void*)(unsigned long)&_new, (const void*)(unsigned long)&_target };
#endif
#endif
/* some systems lack raw clock */
#ifndef CLOCK_MONOTONIC_RAW
#define CLOCK_MONOTONIC_RAW (CLOCK_MONOTONIC + 1)
#endif
#if defined FAKE_UTIME && !defined FAKE_FILE_TIMESTAMPS
#define FAKE_FILE_TIMESTAMPS
#endif
#ifdef FAKE_FILE_TIMESTAMPS
struct utimbuf {
time_t actime; /* access time */
time_t modtime; /* modification time */
};
#endif
#ifdef FAKE_RANDOM
#include <sys/random.h>
#endif
/*
* Per thread variable, which we turn on inside real_* calls to avoid modifying
* time multiple times of for the whole process to prevent faking time
*/
static __thread bool dont_fake = false;
/* Wrapper for function calls, which we want to return system time */
#define DONT_FAKE_TIME(call) \
do { \
bool dont_fake_orig = dont_fake; \
if (!dont_fake) \
{ \
dont_fake = true; \
} \
call; \
dont_fake = dont_fake_orig; \
} while (0)
/* pointers to real (not faked) functions */
static int (*real_stat) (const char *, struct stat *);
static int (*real_fstat) (int, struct stat *);
static int (*real_lstat) (const char *, struct stat *);
static int (*real_xstat) (int, const char *, struct stat *);
static int (*real_fxstat) (int, int, struct stat *);
static int (*real_fxstatat) (int, int, const char *, struct stat *, int);
static int (*real_lxstat) (int, const char *, struct stat *);
static int (*real_xstat64) (int, const char *, struct stat64 *);
static int (*real_fxstat64) (int, int , struct stat64 *);
static int (*real_fxstatat64) (int, int , const char *, struct stat64 *, int);
static int (*real_lxstat64) (int, const char *, struct stat64 *);
static time_t (*real_time) (time_t *);
static int (*real_ftime) (struct timeb *);
static int (*real_gettimeofday) (struct timeval *, void *);
static int (*real_clock_gettime) (clockid_t clk_id, struct timespec *tp);
static int (*real_timespec_get) (struct timespec *ts, int base);
#ifdef FAKE_INTERNAL_CALLS
static int (*real___ftime) (struct timeb *);
static int (*real___gettimeofday) (struct timeval *, void *);
static int (*real___clock_gettime) (clockid_t clk_id, struct timespec *tp);
#endif
#ifdef FAKE_PTHREAD
static int (*real_pthread_cond_timedwait_225) (pthread_cond_t *, pthread_mutex_t*, struct timespec *);
static int (*real_pthread_cond_timedwait_232) (pthread_cond_t *, pthread_mutex_t*, struct timespec *);
static int (*real_pthread_cond_init_232) (pthread_cond_t *restrict, const pthread_condattr_t *restrict);
static int (*real_pthread_cond_destroy_232) (pthread_cond_t *);
static pthread_rwlock_t monotonic_conds_lock;
#endif
#ifndef __APPLEOSX__
#ifdef FAKE_TIMERS
static int (*real_timer_settime_22) (int timerid, int flags, const struct itimerspec *new_value,
struct itimerspec * old_value);
static int (*real_timer_settime_233) (timer_t timerid, int flags,
const struct itimerspec *new_value,
struct itimerspec * old_value);
static int (*real_timer_gettime_22) (int timerid,
struct itimerspec *curr_value);
static int (*real_timer_gettime_233) (timer_t timerid,
struct itimerspec *curr_value);
static int (*real_timerfd_settime) (int fd, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value);
static int (*real_timerfd_gettime) (int fd,
struct itimerspec *curr_value);
#endif
#endif
#ifdef FAKE_SLEEP
static int (*real_nanosleep) (const struct timespec *req, struct timespec *rem);
#ifndef __APPLE__
static int (*real_clock_nanosleep) (clockid_t clock_id, int flags, const struct timespec *req, struct timespec *rem);
#endif
static int (*real_usleep) (useconds_t usec);
static unsigned int (*real_sleep) (unsigned int seconds);
static unsigned int (*real_alarm) (unsigned int seconds);
static int (*real_poll) (struct pollfd *, nfds_t, int);
static int (*real_ppoll) (struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);
#ifdef __linux__
static int (*real_epoll_wait) (int epfd, struct epoll_event *events, int maxevents, int timeout);
static int (*real_epoll_pwait) (int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask);
#endif
static int (*real_select) (int nfds, fd_set *restrict readfds,
fd_set *restrict writefds,
fd_set *restrict errorfds,
struct timeval *restrict timeout);
#ifdef __linux__
static int (*real_pselect) (int nfds, fd_set *restrict readfds,
fd_set *restrict writefds,
fd_set *restrict errorfds,
const struct timespec *timeout,
const sigset_t *sigmask);
#endif
static int (*real_sem_timedwait) (sem_t*, const struct timespec*);
#endif
#ifdef __APPLEOSX__
static int (*real_clock_get_time) (clock_serv_t clock_serv, mach_timespec_t *cur_timeclockid_t);
static int apple_clock_gettime (clockid_t clk_id, struct timespec *tp);
static clock_serv_t clock_serv_real;
#endif
#ifdef FAKE_FILE_TIMESTAMPS
static int (*real_utimes) (const char *filename, const struct timeval times[2]);
static int (*real_utime) (const char *filename, const struct utimbuf *times);
static int (*real_utimensat) (int dirfd, const char *filename, const struct timespec times[2], int flags);
static int (*real_futimens) (int fd, const struct timespec times[2]);
#endif
#ifdef FAKE_RANDOM
static ssize_t (*real_getrandom) (void *buf, size_t buflen, unsigned int flags);
static int (*real_getentropy) (void *buffer, size_t length);
#endif
#ifdef FAKE_PID
static pid_t (*real_getpid) ();
#endif
#ifdef INTERCEPT_SYSCALL
static long (*real_syscall) (long, ...);
#endif
static bool check_missing_real(const char *name, bool missing)
{
if (missing)
{ /* dlsym() failed */
#ifdef DEBUG
(void) fprintf(stderr, "faketime problem: original %s not found.\n", name);
#else
(void) name; /* unused */
#endif
return false;
}
return true;
}
#define CHECK_MISSING_REAL(name) \
check_missing_real(#name, (NULL == real_##name))
static int initialized = 0;
/* prototypes */
static int fake_gettimeofday(struct timeval *tv);
static int fake_clock_gettime(clockid_t clk_id, struct timespec *tp);
int read_config_file();
/** Semaphore protecting shared data */
static sem_t *shared_sem = NULL;
/** Data shared among faketime-spawned processes */
static struct ft_shared_s *ft_shared = NULL;
/** Storage format for timestamps written to file. Big endian. */
struct saved_timestamp
{
int64_t sec;
uint64_t nsec;
};
static inline void timespec_from_saved (struct timespec *tp,
struct saved_timestamp *saved)
{
/* read as big endian */
tp->tv_sec = be64toh(saved->sec);
tp->tv_nsec = be64toh(saved->nsec);
}
/** Saved timestamps */
static struct saved_timestamp *stss = NULL;
static size_t infile_size;
static bool infile_set = false;
/** File fd to save timestamps to */
static int outfile = -1;
static bool limited_faking = false;
static long callcounter = 0;
static long ft_start_after_secs = -1;
static long ft_stop_after_secs = -1;
static long ft_start_after_ncalls = -1;
static long ft_stop_after_ncalls = -1;
static bool spawnsupport = false;
static int spawned = 0;
static char ft_spawn_target[1024];
static long ft_spawn_secs = -1;
static long ft_spawn_ncalls = -1;
#ifdef __ARM_ARCH
static int fake_monotonic_clock = 0;
#else
static int fake_monotonic_clock = 1;
#endif
static int cache_enabled = 1;
static int cache_duration = 10; /* cache fake time input for 10 seconds */
static int force_cache_expiration = 0;
/*
* Static timespec to store our startup time, followed by a load-time library
* initialization declaration.
*/
#ifndef CLOCK_BOOTTIME
static struct system_time_s ftpl_starttime = {{0, -1}, {0, -1}, {0, -1}};
static struct system_time_s ftpl_timecache = {{0, -1}, {0, -1}, {0, -1}};
static struct system_time_s ftpl_faketimecache = {{0, -1}, {0, -1}, {0, -1}};
#else
static struct system_time_s ftpl_starttime = {{0, -1}, {0, -1}, {0, -1}, {0, -1}};
static struct system_time_s ftpl_timecache = {{0, -1}, {0, -1}, {0, -1}, {0, -1}};
static struct system_time_s ftpl_faketimecache = {{0, -1}, {0, -1}, {0, -1}, {0, -1}};
#endif
static char user_faked_time_fmt[BUFSIZ] = {0};
/* User supplied base time to fake */
static struct timespec user_faked_time_timespec = {0, -1};
/* User supplied base time is set */
static bool user_faked_time_set = false;
static char user_faked_time_saved[BUFFERLEN] = {0};
/* Fractional user offset provided through FAKETIME env. var. */
static struct timespec user_offset = {0, -1};
/* Speed up or slow down clock */
static double user_rate = 1.0;
static bool user_rate_set = false;
static struct timespec user_per_tick_inc = {0, -1};
static bool user_per_tick_inc_set = false;
enum ft_mode_t {FT_FREEZE, FT_START_AT, FT_NOOP} ft_mode = FT_FREEZE;
/* Time to fake is not provided through FAKETIME env. var. */
static bool parse_config_file = true;
static void ft_cleanup (void) __attribute__ ((destructor));
static void ftpl_init (void) __attribute__ ((constructor));
/*
* =======================================================================
* Shared memory related functions === SHM
* =======================================================================
*/
static bool shmCreator = false;
static void ft_shm_create(void) {
char sem_name[256], shm_name[256], sem_nameT[256], shm_nameT[256];
int shm_fdN;
sem_t *semN;
struct ft_shared_s *ft_sharedN;
char shared_objsN[513];
sem_t *shared_semT = NULL;
pid_t pid;
#ifdef FAKE_PID
pid = real_getpid();
#else
pid = getpid();
#endif
snprintf(sem_name, 255, "/faketime_sem_%ld", (long)pid);
snprintf(shm_name, 255, "/faketime_shm_%ld", (long)pid);
if (SEM_FAILED == (semN = sem_open(sem_name, O_CREAT|O_EXCL, S_IWUSR|S_IRUSR, 1)))
{ /* silently fail on platforms that do not support sem_open() */
return;
}
/* create shm */
if (-1 == (shm_fdN = shm_open(shm_name, O_CREAT|O_EXCL|O_RDWR, S_IWUSR|S_IRUSR)))
{
perror("libfaketime: In ft_shm_create(), shm_open failed");
exit(EXIT_FAILURE);
}
/* set shm size */
if (-1 == ftruncate(shm_fdN, sizeof(uint64_t)))
{
perror("libfaketime: In ft_shm_create(), ftruncate failed");
exit(EXIT_FAILURE);
}
/* map shm */
if (MAP_FAILED == (ft_sharedN = mmap(NULL, sizeof(struct ft_shared_s), PROT_READ|PROT_WRITE,
MAP_SHARED, shm_fdN, 0)))
{
perror("libfaketime: In ft_shm_create(), mmap failed");
exit(EXIT_FAILURE);
}
if (sem_wait(semN) == -1)
{
perror("libfaketime: In ft_shm_create(), sem_wait failed");
exit(EXIT_FAILURE);
}
/* init elapsed time ticks to zero */
ft_sharedN->ticks = 0;
ft_sharedN->file_idx = 0;
ft_sharedN->start_time.real.tv_sec = 0;
ft_sharedN->start_time.real.tv_nsec = -1;
ft_sharedN->start_time.mon.tv_sec = 0;
ft_sharedN->start_time.mon.tv_nsec = -1;
ft_sharedN->start_time.mon_raw.tv_sec = 0;
ft_sharedN->start_time.mon_raw.tv_nsec = -1;
if (-1 == munmap(ft_sharedN, (sizeof(struct ft_shared_s))))
{
perror("libfaketime: In ft_shm_create(), munmap failed");
exit(EXIT_FAILURE);
}
if (sem_post(semN) == -1)
{
perror("libfaketime: In ft_shm_create(), sem_post failed");
exit(EXIT_FAILURE);
}
snprintf(shared_objsN, sizeof(shared_objsN), "%s %s", sem_name, shm_name);
int semSafetyCheckPassed = 0;
sem_close(semN);
sscanf(shared_objsN, "%255s %255s", sem_nameT, shm_nameT);
if (SEM_FAILED == (shared_semT = sem_open(sem_nameT, 0)))
{
fprintf(stderr, "libfaketime: In ft_shm_create(), non-fatal sem_open issue with %s", sem_nameT);
}
else {
semSafetyCheckPassed = 1;
sem_close(shared_semT);
}
if (semSafetyCheckPassed == 1) {
setenv("FAKETIME_SHARED", shared_objsN, true);
shmCreator = true;
}
}
static void ft_shm_destroy(void)
{
char sem_name[256], shm_name[256], *ft_shared_env = getenv("FAKETIME_SHARED");
if (ft_shared_env != NULL)
{
if (sscanf(ft_shared_env, "%255s %255s", sem_name, shm_name) < 2)
{
printf("libfaketime: In ft_shm_destroy(), error parsing semaphore name and shared memory id from string: %s", ft_shared_env);
exit(1);
}
/*
To avoid shared memory / semaphores left after quitting, we have to clean
up here similar to how the faketime wrapper does.
However, there is no guarantee that all child processes have quit before
we clean up here, which potentially leaves us in a stale state.
Since there is no easy solution for this problem (see issue #56),
ft_shm_init() below at least tries to handle this carefully.
*/
sem_unlink(sem_name);
shm_unlink(shm_name);
unsetenv("FAKETIME_SHARED");
}
}
static void ft_shm_init (void)
{
int ticks_shm_fd;
char sem_name[256], shm_name[256], *ft_shared_env = getenv("FAKETIME_SHARED");
sem_t *shared_semR = NULL;
static int nt=1;
/* create semaphore and shared memory locally unless it has been passed along */
if (ft_shared_env == NULL)
{
ft_shm_create();
ft_shared_env = getenv("FAKETIME_SHARED");
}
/* check for stale semaphore / shared memory information */
if (ft_shared_env != NULL)
{
if (sscanf(ft_shared_env, "%255s %255s", sem_name, shm_name) < 2)
{
printf("libfaketime: In ft_shm_init(), error parsing semaphore name and shared memory id from string: %s", ft_shared_env);
exit(1);
}
if (SEM_FAILED == (shared_semR = sem_open(sem_name, 0))) /* gone stale? */
{
ft_shm_create();
ft_shared_env = getenv("FAKETIME_SHARED");
}
else
{
sem_close(shared_semR);
}
}
/* process the semaphore / shared memory information */
if (ft_shared_env != NULL)
{
if (sscanf(ft_shared_env, "%255s %255s", sem_name, shm_name) < 2)
{
printf("libfaketime: In ft_shm_init(), error parsing semaphore name and shared memory id from string: %s", ft_shared_env);
exit(1);
}
if (SEM_FAILED == (shared_sem = sem_open(sem_name, 0)))
{
if (shmCreator)
{
perror("libfaketime: In ft_shm_init(), sem_open failed");
fprintf(stderr, "libfaketime: sem_name was %s, created locally: %s\n", sem_name, shmCreator ? "true":"false");
fprintf(stderr, "libfaketime: parsed from env: %s\n", ft_shared_env);
exit(1);
}
else
{
nt++;
if (nt > 3)
{
perror("libfaketime: In ft_shm_init(), sem_open failed and recreation attempts failed");
fprintf(stderr, "libfaketime: sem_name was %s, created locally: %s\n", sem_name, shmCreator ? "true":"false");
exit(1);
}
else{
ft_shm_init();
return;
}
}
}
if (-1 == (ticks_shm_fd = shm_open(shm_name, O_CREAT|O_RDWR, S_IWUSR|S_IRUSR)))
{
perror("libfaketime: In ft_shm_init(), shm_open failed");
exit(1);
}
if (MAP_FAILED == (ft_shared = mmap(NULL, sizeof(struct ft_shared_s), PROT_READ|PROT_WRITE,
MAP_SHARED, ticks_shm_fd, 0)))
{
perror("libfaketime: In ft_shm_init(), mmap failed");
exit(1);
}
}
}
static void ft_cleanup (void)
{
/* detach from shared memory */
if (ft_shared != NULL)
{
munmap(ft_shared, sizeof(uint64_t));
}
if (stss != NULL)
{
munmap(stss, infile_size);
}
if (shared_sem != NULL)
{
sem_close(shared_sem);
}
#ifdef FAKE_PTHREAD
if (pthread_rwlock_destroy(&monotonic_conds_lock) != 0) {
fprintf(stderr, "libfaketime: In ft_cleanup(), monotonic_conds_lock destroy failed\n");
exit(-1);
}
#endif
if (shmCreator == true) ft_shm_destroy();
}
/*
* =======================================================================
* Get monotonic faketime setting === GETENV
* =======================================================================
*/
static void get_fake_monotonic_setting(int* current_value)
{
char *tmp_env;
if ((tmp_env = getenv("FAKETIME_DONT_FAKE_MONOTONIC")) != NULL
|| (tmp_env = getenv("DONT_FAKE_MONOTONIC")) != NULL)
{
if (0 == strcmp(tmp_env, "1"))
{
(*current_value) = 0;
}
else
{
(*current_value) = 1;
}
}
}
/*
* =======================================================================
* Internal time retrieval === INTTIME
* =======================================================================
*/
/* Get system time from system for all clocks */
static void system_time_from_system (struct system_time_s * systime)
{
#ifdef __APPLEOSX__
/* from https://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x */
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_serv_real);
(*real_clock_get_time)(clock_serv_real, &mts);
systime->real.tv_sec = mts.tv_sec;
systime->real.tv_nsec = mts.tv_nsec;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
(*real_clock_get_time)(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
systime->mon.tv_sec = mts.tv_sec;
systime->mon.tv_nsec = mts.tv_nsec;
systime->mon_raw.tv_sec = mts.tv_sec;
systime->mon_raw.tv_nsec = mts.tv_nsec;
#else
DONT_FAKE_TIME((*real_clock_gettime)(CLOCK_REALTIME, &systime->real))
;
DONT_FAKE_TIME((*real_clock_gettime)(CLOCK_MONOTONIC, &systime->mon))
;
DONT_FAKE_TIME((*real_clock_gettime)(CLOCK_MONOTONIC_RAW, &systime->mon_raw))
;
#ifdef CLOCK_BOOTTIME
DONT_FAKE_TIME((*real_clock_gettime)(CLOCK_BOOTTIME, &systime->boot))
;
#endif
#endif
}
static void next_time(struct timespec *tp, struct timespec *ticklen)
{
if (shared_sem != NULL)
{
struct timespec inc;
/* lock */
if (sem_wait(shared_sem) == -1)
{
if (errno == EINTR)
{
return next_time(tp, ticklen);
}
else
{
perror("libfaketime: In next_time(), sem_wait failed");
exit(1);
}
}
/* calculate and update elapsed time */
timespecmul(ticklen, ft_shared->ticks, &inc);
timespecadd(&user_faked_time_timespec, &inc, tp);
(ft_shared->ticks)++;
/* unlock */
if (sem_post(shared_sem) == -1)
{
perror("libfaketime: In next_time(), sem_post failed");
exit(1);
}
}
}
/*
* =======================================================================
* Saving & loading time === SAVE
* =======================================================================
*/
static void save_time(struct timespec *tp)
{
if ((shared_sem != NULL) && (outfile != -1))
{
struct saved_timestamp time_write;
ssize_t written;
size_t n = 0;
time_write.sec = htobe64(tp->tv_sec);
time_write.nsec = htobe64(tp->tv_nsec);
/* lock */
if (sem_wait(shared_sem) == -1)
{
if (errno == EINTR)
{
return save_time(tp);
}
else
{
perror("libfaketime: In save_time(), sem_wait failed");
exit(1);
}
}
lseek(outfile, 0, SEEK_END);
do
{
written = write(outfile, &(((char*)&time_write)[n]), sizeof(time_write) - n);
}
while (((written == -1) && (errno == EINTR)) ||
(sizeof(time_write) < (n += written)));
if ((written == -1) || (n < sizeof(time_write)))
{
perror("libfaketime: In save_time(), saving timestamp to file failed");
}
/* unlock */
if (sem_post(shared_sem) == -1)
{
perror("libfaketime: In save_time(), sem_post failed");
exit(1);
}
}
}
/*
* Provide faked time from file.
* @return time is set from filen
*/
static bool load_time(struct timespec *tp)
{
bool ret = false;
if ((shared_sem != NULL) && (infile_set))
{
/* lock */
if (sem_wait(shared_sem) == -1)
{
if (errno == EINTR)
{
return load_time(tp);
}
else
{
perror("libfaketime: In load_time(), sem_wait failed");
exit(1);
}
}
if ((sizeof(stss[0]) * (ft_shared->file_idx + 1)) > infile_size)
{
/* we are out of timestamps to replay, return to faking time by rules
* using last timestamp from file as the user provided timestamp */
timespec_from_saved(&user_faked_time_timespec, &stss[(infile_size / sizeof(stss[0])) - 1 ]);
if (ft_shared->ticks == 0)
{
/* we set shared memory to stop using infile */
ft_shared->ticks = 1;
system_time_from_system(&ftpl_starttime);
ft_shared->start_time = ftpl_starttime;
}
else
{
ftpl_starttime = ft_shared->start_time;
}
munmap(stss, infile_size);
infile_set = false;
}
else
{
timespec_from_saved(tp, &stss[ft_shared->file_idx]);
ft_shared->file_idx++;
ret = true;
}
/* unlock */
if (sem_post(shared_sem) == -1)
{
perror("libfaketime: In load_time(), sem_post failed");
exit(1);
}
}
return ret;
}
/*
* =======================================================================
* Faked system functions: file related === FAKE(FILE)
* =======================================================================
*/
#ifdef FAKE_STAT
#ifndef NO_ATFILE
#ifndef _ATFILE_SOURCE
#define _ATFILE_SOURCE
#endif
#include <fcntl.h> /* Definition of AT_* constants */
#endif
#include <sys/stat.h>
static int fake_stat_disabled = 0;
static int fake_utime_disabled = 1;
static bool user_per_tick_inc_set_backup = false;
void lock_for_stat()
{
if (shared_sem != NULL)
{
if (sem_wait(shared_sem) == -1)
{
if (errno == EINTR)
{
return lock_for_stat();
}
else
{
perror("libfaketime: In lock_for_stat(), sem_wait failed");
exit(1);
}
}
}
user_per_tick_inc_set_backup = user_per_tick_inc_set;
user_per_tick_inc_set = false;
return;
}
void unlock_for_stat()
{
user_per_tick_inc_set = user_per_tick_inc_set_backup;
if (shared_sem != NULL)
{
if (sem_post(shared_sem) == -1)
{
perror("libfaketime: In unlock_for_stat(), sem_post failed");
exit(1);
}
}
return;
}
#define FAKE_STRUCT_STAT_TIME(which) { \
struct timespec t = {buf->st_##which##time, \
buf->st_##which##timensec}; \
fake_clock_gettime(CLOCK_REALTIME, &t); \
buf->st_##which##time = t.tv_sec; \
buf->st_##which##timensec = t.tv_nsec; \
} while (0)
static inline void fake_statbuf (struct stat *buf) {
#ifndef st_atime
lock_for_stat();
FAKE_STRUCT_STAT_TIME(c);
FAKE_STRUCT_STAT_TIME(a);
FAKE_STRUCT_STAT_TIME(m);
unlock_for_stat();
#else
lock_for_stat();
fake_clock_gettime(CLOCK_REALTIME, &buf->st_ctim);
fake_clock_gettime(CLOCK_REALTIME, &buf->st_atim);
fake_clock_gettime(CLOCK_REALTIME, &buf->st_mtim);
unlock_for_stat();
#endif
}
static inline void fake_stat64buf (struct stat64 *buf) {
#ifndef st_atime
lock_for_stat();
FAKE_STRUCT_STAT_TIME(c);
FAKE_STRUCT_STAT_TIME(a);
FAKE_STRUCT_STAT_TIME(m);
unlock_for_stat();
#else
lock_for_stat();
fake_clock_gettime(CLOCK_REALTIME, &buf->st_ctim);
fake_clock_gettime(CLOCK_REALTIME, &buf->st_atim);
fake_clock_gettime(CLOCK_REALTIME, &buf->st_mtim);
unlock_for_stat();
#endif
}
#define STAT_HANDLER_COMMON(name, buf, fake_statbuf, ...) \
if (!initialized) \
{ \
ftpl_init(); \
} \
if (!CHECK_MISSING_REAL(name)) return -1; \
\
int result; \
DONT_FAKE_TIME(result = real_##name(__VA_ARGS__)); \
if (result == -1) \
{ \
return -1; \
} \
\
if (buf != NULL) \
{ \
if (!fake_stat_disabled) \
{ \
if (!dont_fake) fake_statbuf(buf); \
} \
} \
\
return result;
#define STAT_HANDLER(name, buf, ...) \
STAT_HANDLER_COMMON(name, buf, fake_statbuf, __VA_ARGS__)
#define STAT64_HANDLER(name, buf, ...) \
STAT_HANDLER_COMMON(name, buf, fake_stat64buf, __VA_ARGS__)
int stat (const char *path, struct stat *buf)
{
STAT_HANDLER(stat, buf, path, buf);
}
int fstat (int fildes, struct stat *buf)
{
STAT_HANDLER(fstat, buf, fildes, buf);
}
int lstat (const char *path, struct stat *buf)
{
STAT_HANDLER(lstat, buf, path, buf);
}
/* Contributed by Philipp Hachtmann in version 0.6 */
int __xstat (int ver, const char *path, struct stat *buf)
{
STAT_HANDLER(xstat, buf, ver, path, buf);
}
/* Contributed by Philipp Hachtmann in version 0.6 */
int __fxstat (int ver, int fildes, struct stat *buf)
{
STAT_HANDLER(fxstat, buf, ver, fildes, buf);
}
/* Added in v0.8 as suggested by Daniel Kahn Gillmor */
#ifndef NO_ATFILE
int __fxstatat(int ver, int fildes, const char *filename, struct stat *buf, int flag)
{
STAT_HANDLER(fxstatat, buf, ver, fildes, filename, buf, flag);
}
#endif
/* Contributed by Philipp Hachtmann in version 0.6 */
int __lxstat (int ver, const char *path, struct stat *buf)
{
STAT_HANDLER(lxstat, buf, ver, path, buf);
}
/* Contributed by Philipp Hachtmann in version 0.6 */
int __xstat64 (int ver, const char *path, struct stat64 *buf)
{
STAT64_HANDLER(xstat64, buf, ver, path, buf);
}
/* Contributed by Philipp Hachtmann in version 0.6 */
int __fxstat64 (int ver, int fildes, struct stat64 *buf)
{
STAT64_HANDLER(fxstat64, buf, ver, fildes, buf);
}
/* Added in v0.8 as suggested by Daniel Kahn Gillmor */
#ifndef NO_ATFILE
int __fxstatat64 (int ver, int fildes, const char *filename, struct stat64 *buf, int flag)
{
STAT64_HANDLER(fxstatat64, buf, ver, fildes, filename, buf, flag);
}
#endif
/* Contributed by Philipp Hachtmann in version 0.6 */
int __lxstat64 (int ver, const char *path, struct stat64 *buf)
{
STAT64_HANDLER(lxstat64, buf, ver, path, buf);
}
#endif
#ifdef FAKE_FILE_TIMESTAMPS
int utime(const char *filename, const struct utimbuf *times)
{
if (!initialized)
{
ftpl_init();
}
if (!CHECK_MISSING_REAL(utime)) return -1;
int result;
struct utimbuf ntbuf;
if (fake_utime_disabled)
{
if (times == NULL)
{ /* The user wants their given fake times left alone but they requested NOW, so turn it into fake NOW */
ntbuf.actime = ntbuf.modtime = time(NULL);
times = &ntbuf;
}
}
else if (times != NULL)
{
ntbuf.actime = times->actime - user_offset.tv_sec;
ntbuf.modtime = times->modtime - user_offset.tv_sec;
times = &ntbuf;
}
DONT_FAKE_TIME(result = real_utime(filename, times));
return result;
}
int utimes(const char *filename, const struct timeval times[2])
{
if (!initialized)
{
ftpl_init();
}
if (!CHECK_MISSING_REAL(utimes)) return -1;
int result;
struct timeval tn[2];
if (fake_utime_disabled)
{
if (times == NULL)
{ /* The user wants their given fake times left alone but they requested NOW, so turn it into fake NOW */
fake_gettimeofday(&tn[0]);
tn[1] = tn[0];
times = tn;
}
}
else if (times != NULL)
{
struct timeval user_offset2;
user_offset2.tv_sec = user_offset.tv_sec;
user_offset2.tv_usec = user_offset.tv_nsec / 1000;
timersub(×[0], &user_offset2, &tn[0]);
timersub(×[1], &user_offset2, &tn[1]);
times = tn;
}
DONT_FAKE_TIME(result = real_utimes(filename, times));
return result;
}
/* This conditionally offsets 2 timespec values. The caller's out_times array
* always contains valid translated values, even if in_times was NULL. */
static void fake_two_timespec(const struct timespec in_times[2], struct timespec out_times[2])
{
if (in_times == NULL) /* Translate NULL into 2 UTIME_NOW values */
{
out_times[0].tv_sec = out_times[1].tv_sec = 0;
out_times[0].tv_nsec = out_times[1].tv_nsec = UTIME_NOW;
in_times = out_times;
}
struct timespec now;
now.tv_nsec = UTIME_OMIT; /* Wait to grab the current time to see if it's actually needed */
int j;
for (j = 0; j <= 1; j++)
{
/* We need to preserve 2 special time values in addition to when the user disables utime offsets */
if (fake_utime_disabled || in_times[j].tv_nsec == UTIME_OMIT || in_times[j].tv_nsec == UTIME_NOW)
{
if (fake_utime_disabled && in_times[j].tv_nsec == UTIME_NOW)
{ /* The user wants their given fake times left alone but they requested NOW, so turn it into fake NOW */
if (now.tv_nsec == UTIME_OMIT) /* did we grab "now" yet? */
{
DONT_FAKE_TIME(real_clock_gettime(CLOCK_REALTIME, &now));
}
timeradd2(&now, &user_offset, &out_times[j], n);
}
else if (out_times != in_times)
{ /* Just preserve the input value */
out_times[j] = in_times[j];
}
}
else
{
timersub2(&in_times[j], &user_offset, &out_times[j], n);
}
}
}
int utimensat(int dirfd, const char *filename, const struct timespec times[2], int flags)
{
if (!initialized)
{
ftpl_init();
}
if (!CHECK_MISSING_REAL(utimensat)) return -1;
int result;
struct timespec tn[2];
fake_two_timespec(times, tn);
DONT_FAKE_TIME(result = real_utimensat(dirfd, filename, tn, flags));
return result;
}
int futimens(int fd, const struct timespec times[2])
{
if (!initialized)
{
ftpl_init();
}
if (!CHECK_MISSING_REAL(futimens)) return -1;
int result;
struct timespec tn[2];
fake_two_timespec(times, tn);
DONT_FAKE_TIME(result = real_futimens(fd, tn));
return result;
}
#endif
/*
* =======================================================================
* Faked system functions: sleep/alarm/poll/timer related === FAKE(SLEEP)
* =======================================================================
* Contributed by Balint Reczey in v0.9.5
*/
#ifdef FAKE_SLEEP
/*
* Faked nanosleep()
*/
#ifdef MACOS_DYLD_INTERPOSE
int macos_nanosleep(const struct timespec *req, struct timespec *rem)
#else
int nanosleep(const struct timespec *req, struct timespec *rem)
#endif
{
int result;
struct timespec real_req;
if (!initialized)
{
ftpl_init();
}
if (real_nanosleep == NULL)
{
return -1;
}
if (req != NULL)
{
if (user_rate_set && !dont_fake)
{
timespecmul(req, 1.0 / user_rate, &real_req);
}
else
{
real_req = *req;
}
}
else
{
return -1;
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*nanosleep)(&real_req, rem));
#else
DONT_FAKE_TIME(result = (*real_nanosleep)(&real_req, rem));
#endif
if (result == -1)
{
return result;
}
/* fake returned parts */
if ((rem != NULL) && ((rem->tv_sec != 0) || (rem->tv_nsec != 0)))
{
if (user_rate_set && !dont_fake)
{
timespecmul(rem, user_rate, rem);
}
}
/* return the result to the caller */
return result;
}
#ifndef __APPLE__
/*
* Faked clock_nanosleep()
*/
int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *req, struct timespec *rem)
{
int result;
struct timespec real_req;
if (!initialized)
{
ftpl_init();
}
if (real_clock_nanosleep == NULL)
{
return -1;
}
if (req != NULL)
{
if (flags & TIMER_ABSTIME) /* sleep until absolute time */
{
struct timespec tdiff, timeadj;
timespecsub(req, &user_faked_time_timespec, &timeadj);
if (user_rate_set)
{
timespecmul(&timeadj, 1.0/user_rate, &tdiff);
}
else
{
tdiff = timeadj;
}
if (clock_id == CLOCK_REALTIME)
{
timespecadd(&ftpl_starttime.real, &tdiff, &real_req);
}
else if (clock_id == CLOCK_MONOTONIC)
{
timespecadd(&ftpl_starttime.mon, &tdiff, &real_req);
}
else /* presumably only CLOCK_PROCESS_CPUTIME_ID, leave untouched */
{
real_req = *req;
}
}
else /* sleep for a relative time interval */
{
if (user_rate_set && !dont_fake && ((clock_id == CLOCK_REALTIME) || (clock_id == CLOCK_MONOTONIC))) /* don't touch CLOCK_PROCESS_CPUTIME_ID */
{
timespecmul(req, 1.0 / user_rate, &real_req);
}
else
{
real_req = *req;
}
}
}
else
{
return -1;
}
DONT_FAKE_TIME(result = (*real_clock_nanosleep)(clock_id, flags, &real_req, rem));
if (result == -1)
{
return result;
}
/* fake returned parts */
if ((rem != NULL) && ((rem->tv_sec != 0) || (rem->tv_nsec != 0)))
{
if (user_rate_set && !dont_fake)
{
timespecmul(rem, user_rate, rem);
}
}
/* return the result to the caller */
return result;
}
#endif
/*
* Faked usleep()
*/
#ifdef MACOS_DYLD_INTERPOSE
int macos_usleep(useconds_t usec)
#else
int usleep(useconds_t usec)
#endif
{
int result;
if (!initialized)
{
ftpl_init();
}
if (user_rate_set && !dont_fake)
{
struct timespec real_req;
if (real_nanosleep == NULL)
{
/* fall back to usleep() */
if (real_usleep == NULL)
{
return -1;
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*usleep)((1.0 / user_rate) * usec));
#else
DONT_FAKE_TIME(result = (*real_usleep)((1.0 / user_rate) * usec));
#endif
return result;
}
real_req.tv_sec = usec / 1000000;
real_req.tv_nsec = (usec % 1000000) * 1000;
timespecmul(&real_req, 1.0 / user_rate, &real_req);
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*nanosleep)(&real_req, NULL));
#else
DONT_FAKE_TIME(result = (*real_nanosleep)(&real_req, NULL));
#endif
}
else
{
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*usleep)(usec));
#else
DONT_FAKE_TIME(result = (*real_usleep)(usec));
#endif
}
return result;
}
/*
* Faked sleep()
*/
#ifdef MACOS_DYLD_INTERPOSE
unsigned int macos_sleep(unsigned int seconds)
#else
unsigned int sleep(unsigned int seconds)
#endif
{
if (!initialized)
{
ftpl_init();
}
if (user_rate_set && !dont_fake)
{
if (real_nanosleep == NULL)
{
/* fall back to sleep */
unsigned int ret;
if (real_sleep == NULL)
{
return 0;
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(ret = (*sleep)((1.0 / user_rate) * seconds));
#else
DONT_FAKE_TIME(ret = (*real_sleep)((1.0 / user_rate) * seconds));
#endif
return (user_rate_set && !dont_fake)?(user_rate * ret):ret;
}
else
{
int result;
struct timespec real_req = {seconds, 0}, rem;
timespecmul(&real_req, 1.0 / user_rate, &real_req);
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*nanosleep)(&real_req, &rem));
#else
DONT_FAKE_TIME(result = (*real_nanosleep)(&real_req, &rem));
#endif
if (result == -1)
{
return 0;
}
/* fake returned parts */
if ((rem.tv_sec != 0) || (rem.tv_nsec != 0))
{
timespecmul(&rem, user_rate, &rem);
}
/* return the result to the caller */
return rem.tv_sec;
}
}
else
{
/* no need to fake anything */
unsigned int ret;
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(ret = (*sleep)(seconds));
#else
DONT_FAKE_TIME(ret = (*real_sleep)(seconds));
#endif
return ret;
}
}
/*
* Faked alarm()
* @note due to rounding alarm(2) with faketime -f '+0 x7' won't wait 2/7
* wall clock seconds but 0 seconds
*/
#ifdef MACOS_DYLD_INTERPOSE
unsigned int macos_alarm(unsigned int seconds)
#else
unsigned int alarm(unsigned int seconds)
#endif
{
unsigned int ret;
unsigned int seconds_real = (user_rate_set && !dont_fake)?((1.0 / user_rate) * seconds):seconds;
if (!initialized)
{
ftpl_init();
}
if (real_alarm == NULL)
{
return -1;
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(ret = (*alarm)(seconds_real));
#else
DONT_FAKE_TIME(ret = (*real_alarm)(seconds_real));
#endif
return (user_rate_set && !dont_fake)?(user_rate * ret):ret;
}
/*
* Faked ppoll()
*/
int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout_ts, const sigset_t *sigmask)
{
struct timespec real_timeout, *real_timeout_pt;
int ret;
if (!initialized)
{
ftpl_init();
}
if (real_ppoll == NULL)
{
return -1;
}
if (timeout_ts != NULL)
{
if (user_rate_set && !dont_fake && (timeout_ts->tv_sec > 0))
{
timespecmul(timeout_ts, 1.0 / user_rate, &real_timeout);
real_timeout_pt = &real_timeout;
}
else
{
/* cast away constness */
real_timeout_pt = (struct timespec *)timeout_ts;
}
}
else
{
real_timeout_pt = NULL;
}
DONT_FAKE_TIME(ret = (*real_ppoll)(fds, nfds, real_timeout_pt, sigmask));
return ret;
}
#ifdef __linux__
/*
* Faked epoll_wait()
*/
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout)
{
int ret, real_timeout;
if (!initialized)
{
ftpl_init();
}
if (real_epoll_wait == NULL)
{
return -1;
}
if (user_rate_set && !dont_fake && timeout > 0)
{
real_timeout = (int) timeout * 1.0/user_rate;
}
else
{
real_timeout = timeout;
}
DONT_FAKE_TIME(ret = (*real_epoll_wait)(epfd, events, maxevents, real_timeout));
return ret;
}
/*
* Faked epoll_pwait()
*/
int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask)
{
int ret, real_timeout;
if (!initialized)
{
ftpl_init();
}
if (real_epoll_pwait == NULL)
{
return -1;
}
if (user_rate_set && !dont_fake && timeout > 0)
{
real_timeout = (int) timeout * 1.0/user_rate;
}
else
{
real_timeout = timeout;
}
DONT_FAKE_TIME(ret = (*real_epoll_pwait)(epfd, events, maxevents, real_timeout, sigmask));
return ret;
}
#endif
/*
* Faked poll()
*/
#ifdef MACOS_DYLD_INTERPOSE
int macos_poll(struct pollfd *fds, nfds_t nfds, int timeout)
#else
int poll(struct pollfd *fds, nfds_t nfds, int timeout)
#endif
{
int ret, timeout_real = (user_rate_set && !dont_fake && (timeout > 0))?(timeout / user_rate):timeout;
if (!initialized)
{
ftpl_init();
}
if (real_poll == NULL)
{
return -1;
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(ret = (*poll)(fds, nfds, timeout_real));
#else
DONT_FAKE_TIME(ret = (*real_poll)(fds, nfds, timeout_real));
#endif
return ret;
}
/*
* Faked select()
*/
#ifdef MACOS_DYLD_INTERPOSE
int macos_select(int nfds, fd_set *readfds,
fd_set *writefds,
fd_set *errorfds,
struct timeval *timeout)
#else
int select(int nfds, fd_set *readfds,
fd_set *writefds,
fd_set *errorfds,
struct timeval *timeout)
#endif
{
int ret;
struct timeval timeout_real;
if (!initialized)
{
ftpl_init();
}
if (real_select == NULL)
{
return -1;
}
if (timeout != NULL)
{
if (user_rate_set && !dont_fake && (timeout->tv_sec > 0 || timeout->tv_usec > 0))
{
struct timespec ts;
ts.tv_sec = timeout->tv_sec;
ts.tv_nsec = timeout->tv_usec * 1000;
timespecmul(&ts, 1.0 / user_rate, &ts);
timeout_real.tv_sec = ts.tv_sec;
timeout_real.tv_usec = ts.tv_nsec / 1000;
}
else
{
timeout_real.tv_sec = timeout->tv_sec;
timeout_real.tv_usec = timeout->tv_usec;
}
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(ret = (*select)(nfds, readfds, writefds, errorfds, timeout == NULL ? timeout : &timeout_real));
#else
DONT_FAKE_TIME(ret = (*real_select)(nfds, readfds, writefds, errorfds, timeout == NULL ? timeout : &timeout_real));
#endif
return ret;
}
#ifdef __linux__
/*
* Faked pselect()
*/
int pselect(int nfds, fd_set *readfds,
fd_set *writefds,
fd_set *errorfds,
const struct timespec *timeout,
const sigset_t *sigmask)
{
int ret;
struct timespec timeout_real;
if (!initialized)
{
ftpl_init();
}
if (real_pselect == NULL)
{
return -1;
}
if (timeout != NULL)
{
if (user_rate_set && !dont_fake && (timeout->tv_sec > 0 || timeout->tv_nsec > 0))
{
timespecmul(timeout, 1.0 / user_rate, &timeout_real);
}
else
{
timeout_real.tv_sec = timeout->tv_sec;
timeout_real.tv_nsec = timeout->tv_nsec;
}
}
DONT_FAKE_TIME(ret = (*real_pselect)(nfds, readfds, writefds, errorfds, timeout == NULL ? timeout : &timeout_real, sigmask));
return ret;
}
#endif
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout)
{
int result;
struct timespec real_abs_timeout, *real_abs_timeout_pt;
/* sanity check */
if (abs_timeout == NULL)
{
return -1;
}
if (!CHECK_MISSING_REAL(sem_timedwait)) return -1;
if (!dont_fake)
{
struct timespec tdiff, timeadj;
timespecsub(abs_timeout, &user_faked_time_timespec, &tdiff);
if (user_rate_set)
{
timespecmul(&tdiff, user_rate, &timeadj);
}
else
{
timeadj = tdiff;
}
timespecadd(&ftpl_starttime.real, &timeadj, &real_abs_timeout);
real_abs_timeout_pt = &real_abs_timeout;
}
else
{
/* cast away constness */
real_abs_timeout_pt = (struct timespec *)abs_timeout;
}
DONT_FAKE_TIME(result = (*real_sem_timedwait)(sem, real_abs_timeout_pt));
return result;
}
#endif
#ifndef __APPLE__
#ifdef FAKE_TIMERS
/* timer related functions and structures */
typedef union {
int int_member;
timer_t timer_t_member;
} timer_t_or_int;
/*
* Faketime's function implementation's compatibility mode
*/
typedef enum {
FT_COMPAT_GLIBC_2_2,
FT_COMPAT_GLIBC_2_3_3,
FT_FD,
} ft_lib_compat_timer;
/*
* Faked timer_settime()
* Does not affect timer speed when stepping clock with each time() call.
*/
static int
timer_settime_common(timer_t_or_int timerid, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value, ft_lib_compat_timer compat,
int abstime_flag)
{
int result;
struct itimerspec new_real;
struct itimerspec *new_real_pt = &new_real;
if (!initialized)
{
ftpl_init();
}
if (new_value == NULL)
{
new_real_pt = NULL;
}
else if (dont_fake)
{
/* cast away constness */
new_real_pt = (struct itimerspec *)new_value;
}
else
{
/* set it_value */
if ((new_value->it_value.tv_sec != 0) ||
(new_value->it_value.tv_nsec != 0))
{
if (flags & abstime_flag)
{
struct timespec tdiff, timeadj;
timespecsub(&new_value->it_value, &user_faked_time_timespec, &timeadj);
if (user_rate_set)
{
timespecmul(&timeadj, 1.0/user_rate, &tdiff);
}
else
{
tdiff = timeadj;
}
/* only CLOCK_REALTIME is handled */
timespecadd(&ftpl_starttime.real, &tdiff, &new_real.it_value);
}
else
{
if (user_rate_set)
{
timespecmul(&new_value->it_value, 1.0/user_rate, &new_real.it_value);
}
else
{
new_real.it_value = new_value->it_value;
}
}
}
else
{
new_real.it_value = new_value->it_value;
}
/* set it_interval */
if (user_rate_set && ((new_value->it_interval.tv_sec != 0) ||
(new_value->it_interval.tv_nsec != 0)))
{
timespecmul(&new_value->it_interval, 1.0/user_rate, &new_real.it_interval);
}
else
{
new_real.it_interval = new_value->it_interval;
}
}
switch (compat)
{
case FT_COMPAT_GLIBC_2_2:
DONT_FAKE_TIME(result = (*real_timer_settime_22)(timerid.int_member, flags,
new_real_pt, old_value));
break;
case FT_COMPAT_GLIBC_2_3_3:
DONT_FAKE_TIME(result = (*real_timer_settime_233)(timerid.timer_t_member,
flags, new_real_pt, old_value));
break;
case FT_FD:
DONT_FAKE_TIME(result = (*real_timerfd_settime)(timerid.int_member,
flags, new_real_pt, old_value));
break;
default:
result = -1;
break;
}
if (result == -1)
{
return result;
}
/* fake returned parts */
if ((old_value != NULL) && !dont_fake)
{
if ((old_value->it_value.tv_sec != 0) ||
(old_value->it_value.tv_nsec != 0))
{
result = fake_clock_gettime(CLOCK_REALTIME, &old_value->it_value);
}
if (user_rate_set && ((old_value->it_interval.tv_sec != 0) ||
(old_value->it_interval.tv_nsec != 0)))
{
timespecmul(&old_value->it_interval, user_rate, &old_value->it_interval);
}
}
/* return the result to the caller */
return result;
}
/*
* Faked timer_settime() compatible with implementation in GLIBC 2.2
*/
int timer_settime_22(int timerid, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timer_settime_22 == NULL)
{
return -1;
}
else
{
return (timer_settime_common((timer_t_or_int)timerid, flags, new_value, old_value,
FT_COMPAT_GLIBC_2_2, TIMER_ABSTIME));
}
}
/*
* Faked timer_settime() compatible with implementation in GLIBC 2.3.3
*/
int timer_settime_233(timer_t timerid, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timer_settime_233 == NULL)
{
return -1;
}
else
{
return (timer_settime_common((timer_t_or_int)timerid, flags, new_value, old_value,
FT_COMPAT_GLIBC_2_3_3, TIMER_ABSTIME));
}
}
/*
* Faked timer_gettime()
* Does not affect timer speed when stepping clock with each time() call.
*/
int timer_gettime_common(timer_t_or_int timerid, struct itimerspec *curr_value, ft_lib_compat_timer compat)
{
int result;
if (!initialized)
{
ftpl_init();
}
if (real_timer_gettime_233 == NULL)
{
return -1;
}
switch (compat)
{
case FT_COMPAT_GLIBC_2_2:
DONT_FAKE_TIME(result = (*real_timer_gettime_22)(timerid.int_member, curr_value));
break;
case FT_COMPAT_GLIBC_2_3_3:
DONT_FAKE_TIME(result = (*real_timer_gettime_233)(timerid.timer_t_member, curr_value));
break;
case FT_FD:
DONT_FAKE_TIME(result = (*real_timerfd_gettime)(timerid.int_member, curr_value));
break;
default:
result = -1;
break;
}
if (result == -1)
{
return result;
}
/* fake returned parts */
if (curr_value != NULL)
{
if (user_rate_set && !dont_fake)
{
timespecmul(&curr_value->it_interval, user_rate, &curr_value->it_interval);
timespecmul(&curr_value->it_value, user_rate, &curr_value->it_value);
}
}
/* return the result to the caller */
return result;
}
/*
* Faked timer_gettime() compatible with implementation in GLIBC 2.2
*/
int timer_gettime_22(timer_t timerid, struct itimerspec *curr_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timer_gettime_22 == NULL)
{
return -1;
}
else
{
return (timer_gettime_common((timer_t_or_int)timerid, curr_value,
FT_COMPAT_GLIBC_2_2));
}
}
/*
* Faked timer_gettime() compatible with implementation in GLIBC 2.3.3
*/
int timer_gettime_233(timer_t timerid, struct itimerspec *curr_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timer_gettime_233 == NULL)
{
return -1;
}
else
{
return (timer_gettime_common((timer_t_or_int)timerid, curr_value,
FT_COMPAT_GLIBC_2_3_3));
}
}
__asm__(".symver timer_gettime_22, timer_gettime@GLIBC_2.2");
__asm__(".symver timer_gettime_233, timer_gettime@@GLIBC_2.3.3");
__asm__(".symver timer_settime_22, timer_settime@GLIBC_2.2");
__asm__(".symver timer_settime_233, timer_settime@@GLIBC_2.3.3");
#ifdef __linux__
/*
* Faked timerfd_settime
*/
int timerfd_settime(int fd, int flags,
const struct itimerspec *new_value,
struct itimerspec *old_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timerfd_settime == NULL)
{
return -1;
}
else
{
return (timer_settime_common((timer_t_or_int)fd, flags, new_value, old_value, FT_FD,
TFD_TIMER_ABSTIME));
}
}
/*
* Faked timerfd_gettime()
*/
int timerfd_gettime(int fd, struct itimerspec *curr_value)
{
if (!initialized)
{
ftpl_init();
}
if (real_timerfd_gettime == NULL)
{
return -1;
}
else
{
return (timer_gettime_common((timer_t_or_int)fd, curr_value, FT_FD));
}
}
#endif
#endif
#endif
/*
* =======================================================================
* Faked system functions: basic time functions === FAKE(TIME)
* =======================================================================
*/
/*
* time() implementation using clock_gettime()
* @note Does not check for EFAULT, see man 2 time
*/
#ifdef MACOS_DYLD_INTERPOSE
time_t macos_time(time_t *time_tptr)
#else
time_t time(time_t *time_tptr)
#endif
{
struct timespec tp;
time_t result;
if (!initialized)
{
ftpl_init();
}
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*clock_gettime)(CLOCK_REALTIME, &tp));
#else
DONT_FAKE_TIME(result = (*real_clock_gettime)(CLOCK_REALTIME, &tp));
#endif
if (result == -1) return -1;
/* pass the real current time to our faking version, overwriting it */
(void)fake_clock_gettime(CLOCK_REALTIME, &tp);
if (time_tptr != NULL)
{
*time_tptr = tp.tv_sec;
}
return tp.tv_sec;
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_ftime(struct timeb *tb)
#else
int ftime(struct timeb *tb)
#endif
{
struct timespec tp;
int result;
if (!initialized)
{
ftpl_init();
}
/* sanity check */
if (tb == NULL)
return 0; /* ftime() always returns 0, see manpage */
/* Check whether we've got a pointer to the real ftime() function yet */
if (!CHECK_MISSING_REAL(ftime)) return 0;
/* initialize our TZ result with the real current time */
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*ftime)(tb));
#else
DONT_FAKE_TIME(result = (*real_ftime)(tb));
#endif
if (result == -1)
{
return result;
}
DONT_FAKE_TIME(result = (*real_clock_gettime)(CLOCK_REALTIME, &tp));
if (result == -1) return -1;
/* pass the real current time to our faking version, overwriting it */
(void)fake_clock_gettime(CLOCK_REALTIME, &tp);
tb->time = tp.tv_sec;
tb->millitm = tp.tv_nsec / 1000000;
/* return the result to the caller */
return result; /* will always be 0 (see manpage) */
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_gettimeofday(struct timeval *tv, void *tz)
#else
int gettimeofday(struct timeval *tv, void *tz)
#endif
{
int result;
if (!initialized)
{
ftpl_init();
}
/* sanity check */
if (tv == NULL)
{
return -1;
}
/* Check whether we've got a pointer to the real ftime() function yet */
if (!CHECK_MISSING_REAL(gettimeofday)) return -1;
/* initialize our result with the real current time */
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*gettimeofday)(tv, tz));
#else
DONT_FAKE_TIME(result = (*real_gettimeofday)(tv, tz));
#endif
if (result == -1) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
result = fake_gettimeofday(tv);
/* return the result to the caller */
return result;
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_clock_gettime(clockid_t clk_id, struct timespec *tp)
#else
int clock_gettime(clockid_t clk_id, struct timespec *tp)
#endif
{
int result;
static int recursion_depth = 0;
if (!initialized)
{
recursion_depth++;
if (recursion_depth == 2)
{
fprintf(stderr, "libfaketime: Unexpected recursive calls to clock_gettime() without proper initialization. Trying alternative.\n");
DONT_FAKE_TIME(ftpl_init()) ;
}
else if (recursion_depth == 3)
{
fprintf(stderr, "libfaketime: Cannot recover from unexpected recursive calls to clock_gettime().\n");
fprintf(stderr, "libfaketime: Please check whether any other libraries are in use that clash with libfaketime.\n");
fprintf(stderr, "libfaketime: Returning -1 on clock_gettime() to break recursion now... if that does not work, please check other libraries' error handling.\n");
if (tp != NULL)
{
tp->tv_sec = 0;
tp->tv_nsec = 0;
}
return -1;
}
else {
ftpl_init();
}
recursion_depth--;
}
/* sanity check */
if (tp == NULL)
{
return -1;
}
if (!CHECK_MISSING_REAL(clock_gettime)) return -1;
/* initialize our result with the real current time */
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*clock_gettime)(clk_id, tp));
#else
DONT_FAKE_TIME(result = (*real_clock_gettime)(clk_id, tp));
#endif
if (result == -1) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
if (fake_monotonic_clock || (clk_id != CLOCK_MONOTONIC && clk_id != CLOCK_MONOTONIC_RAW
#ifdef CLOCK_MONOTONIC_COARSE
&& clk_id != CLOCK_MONOTONIC_COARSE
#endif
#ifdef CLOCK_BOOTTIME
&& clk_id != CLOCK_BOOTTIME
#endif
))
{
result = fake_clock_gettime(clk_id, tp);
}
/* return the result to the caller */
return result;
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_timespec_get(struct timespec *ts, int base)
#else
int timespec_get(struct timespec *ts, int base)
#endif
{
int result;
if (!initialized)
{
ftpl_init();
}
/* sanity check */
if (ts == NULL)
{
return 0;
}
if (!CHECK_MISSING_REAL(timespec_get)) return 0;
/* initialize our result with the real current time */
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(result = (*timespec_get)(ts, base));
#else
DONT_FAKE_TIME(result = (*real_timespec_get)(ts, base));
#endif
if (result == 0) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
(void)fake_clock_gettime(CLOCK_REALTIME, ts);
/* return the result to the caller */
return result;
}
/*
* =======================================================================
* Parsing the user's faketime requests === PARSE
* =======================================================================
*/
static void parse_ft_string(const char *user_faked_time)
{
struct tm user_faked_time_tm;
char * tmp_time_fmt;
char * nstime_str;
if (!strncmp(user_faked_time, user_faked_time_saved, BUFFERLEN))
{
/* No change but eventually when using FAKETIME_FOLLOW_FILE */
if (user_faked_time[0] != '%')
return;
}
/* check whether the user gave us an absolute time to fake */
switch (user_faked_time[0])
{
default: /* Try and interpret this as a specified time */
if (ft_mode != FT_NOOP) ft_mode = FT_FREEZE;
user_faked_time_tm.tm_isdst = -1;
nstime_str = strptime(user_faked_time, user_faked_time_fmt, &user_faked_time_tm);
if (NULL != nstime_str)
{
user_faked_time_timespec.tv_sec = mktime(&user_faked_time_tm);
user_faked_time_timespec.tv_nsec = 0;
if (nstime_str[0] == '.')
{
double nstime = atof(--nstime_str);
user_faked_time_timespec.tv_nsec = (nstime - floor(nstime)) * SEC_TO_nSEC;
}
user_faked_time_set = true;
}
else
{
fprintf(stderr, "libfaketime: In parse_ft_string(), failed to parse FAKETIME timestamp.\n"
"Please check specification %s with format %s\n", user_faked_time, user_faked_time_fmt);
exit(EXIT_FAILURE);
}
break;
case '+':
case '-': /* User-specified offset */
if (ft_mode != FT_NOOP) ft_mode = FT_START_AT;
/* fractional time offsets contributed by Karl Chen in v0.8 */
double frac_offset = atof(user_faked_time);
/* offset is in seconds by default, but the string may contain
* multipliers...
*/
if (strchr(user_faked_time, 'm') != NULL) frac_offset *= 60;
else if (strchr(user_faked_time, 'h') != NULL) frac_offset *= 60 * 60;
else if (strchr(user_faked_time, 'd') != NULL) frac_offset *= 60 * 60 * 24;
else if (strchr(user_faked_time, 'y') != NULL) frac_offset *= 60 * 60 * 24 * 365;
user_offset.tv_sec = floor(frac_offset);
user_offset.tv_nsec = (frac_offset - user_offset.tv_sec) * SEC_TO_nSEC;
timespecadd(&ftpl_starttime.real, &user_offset, &user_faked_time_timespec);
goto parse_modifiers;
break;
/* Contributed by David North, TDI in version 0.7 */
case '@': /* Specific time, but clock along relative to that starttime */
ft_mode = FT_START_AT;
user_faked_time_tm.tm_isdst = -1;
nstime_str = strptime(&user_faked_time[1], user_faked_time_fmt, &user_faked_time_tm);
if (NULL != nstime_str)
{
user_faked_time_timespec.tv_sec = mktime(&user_faked_time_tm);
user_faked_time_timespec.tv_nsec = 0;
if (nstime_str[0] == '.')
{
double nstime = atof(--nstime_str);
user_faked_time_timespec.tv_nsec = (nstime - floor(nstime)) * SEC_TO_nSEC;
}
}
else
{
fprintf(stderr, "libfaketime: In parse_ft_string(), failed to parse FAKETIME timestamp.\n");
exit(EXIT_FAILURE);
}
/* Reset starttime */
if (NULL == getenv("FAKETIME_DONT_RESET"))
system_time_from_system(&ftpl_starttime);
goto parse_modifiers;
break;
case '%': /* follow file timestamp as suggested by Hitoshi Harada (umitanuki) */
ft_mode = FT_START_AT;
struct stat master_file_stats;
int ret;
if (NULL == getenv("FAKETIME_FOLLOW_FILE"))
{
fprintf(stderr, "libfaketime: %% operator in FAKETIME setting requires environment variable FAKETIME_FOLLOW_FILE set.\n");
exit(1);
}
else
{
DONT_FAKE_TIME(ret = stat(getenv("FAKETIME_FOLLOW_FILE"), &master_file_stats));
if (ret == -1)
{
fprintf(stderr, "libfaketime: Cannot get timestamp of file %s as requested by %% operator.\n", getenv("FAKETIME_FOLLOW_FILE"));
exit(1);
}
else
{
user_faked_time_timespec.tv_sec = master_file_stats.st_mtime;
user_faked_time_timespec.tv_nsec = 0;
}
}
if (NULL == getenv("FAKETIME_DONT_RESET"))
system_time_from_system(&ftpl_starttime);
goto parse_modifiers;
break;
case 'i':
case 'x': /* Only modifiers are passed, don't fall back to strptime */
parse_modifiers:
/* Speed-up / slow-down contributed by Karl Chen in v0.8 */
if (strchr(user_faked_time, 'x') != NULL)
{
user_rate = atof(strchr(user_faked_time, 'x')+1);
user_rate_set = true;
if (NULL != getenv("FAKETIME_XRESET")) {
if (ftpl_timecache.real.tv_nsec >= 0) {
user_faked_time_timespec.tv_sec = ftpl_faketimecache.real.tv_sec;
user_faked_time_timespec.tv_nsec = ftpl_faketimecache.real.tv_nsec;
ftpl_starttime.real.tv_sec = ftpl_timecache.real.tv_sec;
ftpl_starttime.real.tv_nsec = ftpl_timecache.real.tv_nsec;
ftpl_starttime.mon.tv_sec = ftpl_timecache.mon.tv_sec;
ftpl_starttime.mon.tv_nsec = ftpl_timecache.mon.tv_nsec;
ftpl_starttime.mon_raw.tv_sec = ftpl_timecache.mon_raw.tv_sec;
ftpl_starttime.mon_raw.tv_nsec = ftpl_timecache.mon_raw.tv_nsec;
#ifdef CLOCK_BOOTTIME
ftpl_starttime.boot.tv_sec = ftpl_timecache.boot.tv_sec;
ftpl_starttime.boot.tv_nsec = ftpl_timecache.boot.tv_nsec;
#endif
}
}
}
else if (NULL != (tmp_time_fmt = strchr(user_faked_time, 'i')))
{
double tick_inc = atof(tmp_time_fmt + 1);
/* increment time with every time() call */
user_per_tick_inc.tv_sec = floor(tick_inc);
user_per_tick_inc.tv_nsec = (tick_inc - user_per_tick_inc.tv_sec) * SEC_TO_nSEC ;
user_per_tick_inc_set = true;
}
break;
} // end of switch
strncpy(user_faked_time_saved, user_faked_time, BUFFERLEN-1);
user_faked_time_saved[BUFFERLEN-1] = 0;
#ifdef DEBUG
fprintf(stderr, "new FAKETIME: %s\n", user_faked_time_saved);
#endif
}
/*
* =======================================================================
* Initialization === INIT
* =======================================================================
*/
static void ftpl_init(void)
{
char *tmp_env;
bool dont_fake_final;
/* moved up here from below the dlsym calls #130 */
dont_fake = true; // Do not fake times during initialization
dont_fake_final = false;
#ifdef __APPLE__
const char *progname = getprogname();
#else
const char *progname = __progname;
#endif
/* Look up all real_* functions. NULL will mark missing ones. */
real_stat = dlsym(RTLD_NEXT, "stat");
real_lstat = dlsym(RTLD_NEXT, "lstat");
real_fstat = dlsym(RTLD_NEXT, "fstat");
real_xstat = dlsym(RTLD_NEXT, "__xstat");
real_fxstat = dlsym(RTLD_NEXT, "__fxstat");
real_fxstatat = dlsym(RTLD_NEXT, "__fxstatat");
real_lxstat = dlsym(RTLD_NEXT, "__lxstat");
real_xstat64 = dlsym(RTLD_NEXT,"__xstat64");
real_fxstat64 = dlsym(RTLD_NEXT, "__fxstat64");
real_fxstatat64 = dlsym(RTLD_NEXT, "__fxstatat64");
real_lxstat64 = dlsym(RTLD_NEXT, "__lxstat64");
real_time = dlsym(RTLD_NEXT, "time");
real_ftime = dlsym(RTLD_NEXT, "ftime");
real_timespec_get = dlsym(RTLD_NEXT, "timespec_get");
#ifdef FAKE_FILE_TIMESTAMPS
real_utimes = dlsym(RTLD_NEXT, "utimes");
real_utime = dlsym(RTLD_NEXT, "utime");
real_utimensat = dlsym(RTLD_NEXT, "utimensat");
real_futimens = dlsym(RTLD_NEXT, "futimens");
#endif
#if defined(__alpha__) && defined(__GLIBC__)
real_gettimeofday = dlvsym(RTLD_NEXT, "gettimeofday", "GLIBC_2.1");
#else
real_gettimeofday = dlsym(RTLD_NEXT, "gettimeofday");
#endif
#ifdef FAKE_SLEEP
real_nanosleep = dlsym(RTLD_NEXT, "nanosleep");
#ifndef __APPLE__
real_clock_nanosleep = dlsym(RTLD_NEXT, "clock_nanosleep");
#endif
real_usleep = dlsym(RTLD_NEXT, "usleep");
real_sleep = dlsym(RTLD_NEXT, "sleep");
real_alarm = dlsym(RTLD_NEXT, "alarm");
real_poll = dlsym(RTLD_NEXT, "poll");
real_ppoll = dlsym(RTLD_NEXT, "ppoll");
#ifdef linux
real_epoll_wait = dlsym(RTLD_NEXT, "epoll_wait");
real_epoll_pwait = dlsym(RTLD_NEXT, "epoll_pwait");
#endif
real_select = dlsym(RTLD_NEXT, "select");
#ifdef __linux__
real_pselect = dlsym(RTLD_NEXT, "pselect");
#endif
real_sem_timedwait = dlsym(RTLD_NEXT, "sem_timedwait");
#endif
#ifdef FAKE_INTERNAL_CALLS
real___ftime = dlsym(RTLD_NEXT, "__ftime");
# if defined(__alpha__) && defined(__GLIBC__)
real___gettimeofday = dlvsym(RTLD_NEXT, "__gettimeofday", "GLIBC_2.1");
# else
real___gettimeofday = dlsym(RTLD_NEXT, "__gettimeofday");
# endif
real___clock_gettime = dlsym(RTLD_NEXT, "__clock_gettime");
#endif
#ifdef FAKE_RANDOM
real_getrandom = dlsym(RTLD_NEXT, "getrandom");
real_getentropy = dlsym(RTLD_NEXT, "getentropy");
#endif
#ifdef FAKE_PID
real_getpid = dlsym(RTLD_NEXT, "getpid");
#endif
#ifdef INTERCEPT_SYSCALL
real_syscall = dlsym(RTLD_NEXT, "syscall");
#endif
#ifdef FAKE_PTHREAD
#ifdef __GLIBC__
real_pthread_cond_timedwait_225 = dlvsym(RTLD_NEXT, "pthread_cond_timedwait", "GLIBC_2.2.5");
real_pthread_cond_timedwait_232 = dlvsym(RTLD_NEXT, "pthread_cond_timedwait", "GLIBC_2.3.2");
real_pthread_cond_init_232 = dlvsym(RTLD_NEXT, "pthread_cond_init", "GLIBC_2.3.2");
real_pthread_cond_destroy_232 = dlvsym(RTLD_NEXT, "pthread_cond_destroy", "GLIBC_2.3.2");
#endif
if (NULL == real_pthread_cond_timedwait_232)
{
real_pthread_cond_timedwait_232 = dlsym(RTLD_NEXT, "pthread_cond_timedwait");
}
if (NULL == real_pthread_cond_init_232)
{
real_pthread_cond_init_232 = dlsym(RTLD_NEXT, "pthread_cond_init");
}
if (NULL == real_pthread_cond_destroy_232)
{
real_pthread_cond_destroy_232 = dlsym(RTLD_NEXT, "pthread_cond_destroy");
}
if (pthread_rwlock_init(&monotonic_conds_lock,NULL) != 0) {
fprintf(stderr,"monotonic_conds_lock init failed\n");
exit(-1);
}
#endif
#ifdef __APPLEOSX__
real_clock_get_time = dlsym(RTLD_NEXT, "clock_get_time");
real_clock_gettime = apple_clock_gettime;
#else
real_clock_gettime = dlsym(RTLD_NEXT, "__clock_gettime");
if (NULL == real_clock_gettime)
{
real_clock_gettime = dlsym(RTLD_NEXT, "clock_gettime");
}
#ifdef FAKE_TIMERS
#if defined(__sun)
real_timer_gettime_233 = dlsym(RTLD_NEXT, "timer_gettime");
real_timer_settime_233 = dlsym(RTLD_NEXT, "timer_settime");
#else
#ifdef __GLIBC__
real_timer_settime_22 = dlvsym(RTLD_NEXT, "timer_settime","GLIBC_2.2");
real_timer_settime_233 = dlvsym(RTLD_NEXT, "timer_settime","GLIBC_2.3.3");
#endif
if (NULL == real_timer_settime_233)
{
real_timer_settime_233 = dlsym(RTLD_NEXT, "timer_settime");
}
#ifdef __GLIBC__
real_timer_gettime_22 = dlvsym(RTLD_NEXT, "timer_gettime","GLIBC_2.2");
real_timer_gettime_233 = dlvsym(RTLD_NEXT, "timer_gettime","GLIBC_2.3.3");
#endif
if (NULL == real_timer_gettime_233)
{
real_timer_gettime_233 = dlsym(RTLD_NEXT, "timer_gettime");
}
#endif
#ifdef __linux__
real_timerfd_gettime = dlsym(RTLD_NEXT, "timerfd_gettime");
real_timerfd_settime = dlsym(RTLD_NEXT, "timerfd_settime");
#endif
#endif
#endif
#ifdef MACOS_DYLD_INTERPOSE
do_macos_dyld_interpose();
#endif
initialized = 1;
#ifdef FAKE_STATELESS
if (0) ft_shm_init();
#else
ft_shm_init();
#endif
#ifdef FAKE_STAT
if (getenv("NO_FAKE_STAT")!=NULL)
{
fake_stat_disabled = 1; //Note that this is NOT re-checked
}
#endif
#if defined FAKE_FILE_TIMESTAMPS
#ifndef FAKE_UTIME
fake_utime_disabled = 0; // Defaults to enabled w/o FAKE_UTIME define
#endif
if ((tmp_env = getenv("FAKE_UTIME")) != NULL) //Note that this is NOT re-checked
{
if (!*tmp_env || *tmp_env == 'y' || *tmp_env == 'Y' || *tmp_env == 't' || *tmp_env == 'T')
{ /* an empty string or a yes/true value turns off disabling */
fake_utime_disabled = 0;
}
else
{ /* Any other non-number disables the utime functions, but we also support FAKE_UTIME=1 to enable */
fake_utime_disabled = !atoi(tmp_env);
}
}
#endif
if ((tmp_env = getenv("FAKETIME_CACHE_DURATION")) != NULL)
{
cache_duration = atoi(tmp_env);
}
if ((tmp_env = getenv("FAKETIME_NO_CACHE")) != NULL)
{
if (0 == strcmp(tmp_env, "1"))
{
cache_enabled = 0;
}
}
get_fake_monotonic_setting(&fake_monotonic_clock);
/* Check whether we actually should be faking the returned timestamp. */
/* We can prevent faking time for specified commands */
if ((tmp_env = getenv("FAKETIME_SKIP_CMDS")) != NULL)
{
char *skip_cmd, *saveptr, *tmpvar;
/* Don't mess with the env variable directly. */
tmpvar = strdup(tmp_env);
if (tmpvar != NULL)
{
skip_cmd = strtok_r(tmpvar, ",", &saveptr);
while (skip_cmd != NULL)
{
if (0 == strcmp(progname, skip_cmd))
{
ft_mode = FT_NOOP;
dont_fake_final = true;
break;
}
skip_cmd = strtok_r(NULL, ",", &saveptr);
}
free(tmpvar);
tmpvar = NULL;
}
else
{
fprintf(stderr, "Error: Could not copy the environment variable value.\n");
exit(EXIT_FAILURE);
}
}
/* We can limit faking time to specified commands */
if ((tmp_env = getenv("FAKETIME_ONLY_CMDS")) != NULL)
{
char *only_cmd, *saveptr, *tmpvar;
bool cmd_matched = false;
if (getenv("FAKETIME_SKIP_CMDS") != NULL)
{
fprintf(stderr, "Error: Both FAKETIME_SKIP_CMDS and FAKETIME_ONLY_CMDS can't be set.\n");
exit(EXIT_FAILURE);
}
/* Don't mess with the env variable directly. */
tmpvar = strdup(tmp_env);
if (tmpvar != NULL) {
only_cmd = strtok_r(tmpvar, ",", &saveptr);
while (only_cmd != NULL)
{
if (0 == strcmp(progname, only_cmd))
{
cmd_matched = true;
break;
}
only_cmd = strtok_r(NULL, ",", &saveptr);
}
if (!cmd_matched)
{
ft_mode = FT_NOOP;
dont_fake_final = true;
}
free(tmpvar);
} else {
fprintf(stderr, "Error: Could not copy the environment variable value.\n");
exit(EXIT_FAILURE);
}
}
if ((tmp_env = getenv("FAKETIME_START_AFTER_SECONDS")) != NULL)
{
ft_start_after_secs = atol(tmp_env);
limited_faking = true;
}
if ((tmp_env = getenv("FAKETIME_STOP_AFTER_SECONDS")) != NULL)
{
ft_stop_after_secs = atol(tmp_env);
limited_faking = true;
}
if ((tmp_env = getenv("FAKETIME_START_AFTER_NUMCALLS")) != NULL)
{
ft_start_after_ncalls = atol(tmp_env);
limited_faking = true;
}
if ((tmp_env = getenv("FAKETIME_STOP_AFTER_NUMCALLS")) != NULL)
{
ft_stop_after_ncalls = atol(tmp_env);
limited_faking = true;
}
/* check whether we should spawn an external command */
if ((tmp_env = getenv("FAKETIME_SPAWN_TARGET")) != NULL)
{
spawnsupport = true;
(void) strncpy(ft_spawn_target, getenv("FAKETIME_SPAWN_TARGET"), sizeof(ft_spawn_target) - 1);
ft_spawn_target[sizeof(ft_spawn_target) - 1] = 0;
if ((tmp_env = getenv("FAKETIME_SPAWN_SECONDS")) != NULL)
{
ft_spawn_secs = atol(tmp_env);
}
if ((tmp_env = getenv("FAKETIME_SPAWN_NUMCALLS")) != NULL)
{
ft_spawn_ncalls = atol(tmp_env);
}
}
if ((tmp_env = getenv("FAKETIME_SAVE_FILE")) != NULL)
{
if (-1 == (outfile = open(tmp_env, O_RDWR | O_APPEND | O_CLOEXEC | O_CREAT,
S_IWUSR | S_IRUSR)))
{
perror("libfaketime: In ftpl_init(), opening file for saving timestamps failed");
exit(EXIT_FAILURE);
}
}
/* load file only if reading timestamps from it is not finished yet */
if ((tmp_env = getenv("FAKETIME_LOAD_FILE")) != NULL)
{
int infile = -1;
struct stat sb;
if (-1 == (infile = open(tmp_env, O_RDONLY|O_CLOEXEC)))
{
perror("libfaketime: In ftpl_init(), opening file for loading timestamps failed");
exit(EXIT_FAILURE);
}
fstat(infile, &sb);
if (sizeof(stss[0]) > (infile_size = sb.st_size))
{
printf("There are no timestamps in the provided file to load timestamps from");
exit(EXIT_FAILURE);
}
if ((infile_size % sizeof(stss[0])) != 0)
{
printf("File size is not multiple of timestamp size. It is probably damaged.");
exit(EXIT_FAILURE);
}
stss = mmap(NULL, infile_size, PROT_READ, MAP_SHARED, infile, 0);
if (stss == MAP_FAILED)
{
perror("libfaketime: In ftpl_init(), mapping file for loading timestamps failed");
exit(EXIT_FAILURE);
}
infile_set = true;
}
tmp_env = getenv("FAKETIME_FMT");
if (tmp_env == NULL)
{
strcpy(user_faked_time_fmt, "%Y-%m-%d %T");
}
else
{
strncpy(user_faked_time_fmt, tmp_env, BUFSIZ - 1);
user_faked_time_fmt[BUFSIZ - 1] = 0;
}
if (shared_sem != 0)
{
if (sem_wait(shared_sem) == -1)
{
perror("libfaketime: In ftpl_init(), sem_wait failed");
exit(1);
}
if (ft_shared->start_time.real.tv_nsec == -1)
{
/* set up global start time */
system_time_from_system(&ftpl_starttime);
ft_shared->start_time = ftpl_starttime;
}
else
{
/** get preset start time */
ftpl_starttime = ft_shared->start_time;
}
if (sem_post(shared_sem) == -1)
{
perror("libfaketime: In ftpl_init(), sem_post failed");
exit(1);
}
}
else
{
system_time_from_system(&ftpl_starttime);
}
/* fake time supplied as environment variable? */
if (NULL != (tmp_env = getenv("FAKETIME")))
{
parse_config_file = false;
parse_ft_string(tmp_env);
}
else
{
read_config_file();
}
dont_fake = dont_fake_final;
}
/*
* =======================================================================
* Helper functions === HELPER
* =======================================================================
*/
static void remove_trailing_eols(char *line)
{
char *endp = line + strlen(line);
/*
* erase the last char if it's a newline
* or carriage return, and back up.
* keep doing this, but don't back up
* past the beginning of the string.
*/
# define is_eolchar(c) ((c) == '\n' || (c) == '\r')
while (endp > line && is_eolchar(endp[-1]))
{
*--endp = '\0';
}
}
/*
* =======================================================================
* Implementation of faked functions === FAKE(FAKE)
* =======================================================================
*/
#ifdef PTHREAD_SINGLETHREADED_TIME
/*
* To avoid a deadlock if a faketime function is interrupted by a signal while
* holding the lock, we block all signals while the mutex is locked.
* The original_mask field is used to restore the previous set of signals
* after the lock has been released.
* (Prompted by issues with parallel garbage collection in D 2.090. D uses signals
* to freeze all but one thread. The frozen threads may be in faketime operations.)
*/
struct LockedState {
pthread_mutex_t *mutex;
sigset_t original_mask;
};
static void pthread_cleanup_mutex_lock(void *data)
{
struct LockedState *state = data;
pthread_mutex_unlock(state->mutex);
pthread_sigmask(SIG_SETMASK, &state->original_mask, NULL);
}
#endif
int read_config_file()
{
static char user_faked_time[BUFFERLEN]; /* changed to static for caching in v0.6 */
static char custom_filename[BUFSIZ];
static char filename[BUFSIZ];
FILE *faketimerc;
/* check whether there's a .faketimerc in the user's home directory, or
* a system-wide /etc/faketimerc present.
* The /etc/faketimerc handling has been contributed by David Burley,
* Jacob Moorman, and Wayne Davison of SourceForge, Inc. in version 0.6 */
(void) snprintf(custom_filename, BUFSIZ, "%s", getenv("FAKETIME_TIMESTAMP_FILE"));
(void) snprintf(filename, BUFSIZ, "%s/.faketimerc", getenv("HOME"));
if ((faketimerc = fopen(custom_filename, "rt")) != NULL ||
(faketimerc = fopen(filename, "rt")) != NULL ||
(faketimerc = fopen("/etc/faketimerc", "rt")) != NULL)
{
static char line[BUFFERLEN];
while (fgets(line, BUFFERLEN, faketimerc) != NULL)
{
if ((strlen(line) > 1) && (line[0] != ' ') &&
(line[0] != '#') && (line[0] != ';'))
{
remove_trailing_eols(line);
strncpy(user_faked_time, line, BUFFERLEN-1);
user_faked_time[BUFFERLEN-1] = 0;
break;
}
}
fclose(faketimerc);
parse_ft_string(user_faked_time);
return 1;
}
return 0;
}
int fake_clock_gettime(clockid_t clk_id, struct timespec *tp)
{
/* variables used for caching, introduced in version 0.6 */
static time_t last_data_fetch = 0; /* not fetched previously at first call */
static int cache_expired = 1; /* considered expired at first call */
/* Karl Chan's v0.8 sanity check moved here for 0.9.9 */
if (tp == NULL) return -1;
/* create a copy of the timespec containing the real system time for clk_id */
struct timespec tp_save;
tp_save.tv_sec = tp->tv_sec;
tp_save.tv_nsec = tp->tv_nsec;
if (dont_fake) return 0;
/* Per process timers are only sped up or slowed down */
if ((clk_id == CLOCK_PROCESS_CPUTIME_ID ) || (clk_id == CLOCK_THREAD_CPUTIME_ID))
{
if (user_rate_set)
{
timespecmul(tp, user_rate, tp);
}
return 0;
}
// {ret = value; goto abort;} to call matching pthread_cleanup_pop and return value
volatile int ret = INT_MAX;
#ifdef PTHREAD_SINGLETHREADED_TIME
static pthread_mutex_t time_mutex = PTHREAD_MUTEX_INITIALIZER;
// block all signals while locked. prevents deadlocks if signal interrupts in in mid-operation.
sigset_t all_signals, original_mask;
sigfillset(&all_signals);
pthread_sigmask(SIG_SETMASK, &all_signals, &original_mask);
pthread_mutex_lock(&time_mutex);
struct LockedState state = { .mutex = &time_mutex, .original_mask = original_mask };
pthread_cleanup_push(pthread_cleanup_mutex_lock, &state);
#endif
if ((limited_faking &&
((ft_start_after_ncalls != -1) || (ft_stop_after_ncalls != -1))) ||
(spawnsupport && ft_spawn_ncalls))
{
if (callcounter < LONG_MAX) callcounter++;
}
if (limited_faking || spawnsupport)
{
struct timespec tmp_ts;
/* For debugging, output #seconds and #calls */
switch (clk_id)
{
case CLOCK_REALTIME:
#ifdef CLOCK_REALTIME_COARSE
case CLOCK_REALTIME_COARSE:
#endif
timespecsub(tp, &ftpl_starttime.real, &tmp_ts);
break;
case CLOCK_MONOTONIC:
#ifdef CLOCK_MONOTONIC_COARSE
case CLOCK_MONOTONIC_COARSE:
#endif
timespecsub(tp, &ftpl_starttime.mon, &tmp_ts);
break;
case CLOCK_MONOTONIC_RAW:
timespecsub(tp, &ftpl_starttime.mon_raw, &tmp_ts);
break;
#ifdef CLOCK_BOOTTIME
case CLOCK_BOOTTIME:
timespecsub(tp, &ftpl_starttime.boot, &tmp_ts);
break;
#endif
default:
timespecsub(tp, &ftpl_starttime.real, &tmp_ts);
break;
}
if (limited_faking)
{
/* Check whether we actually should be faking the returned timestamp. */
/* fprintf(stderr, "(libfaketime limits -> runtime: %lu, callcounter: %lu\n", (*time_tptr - ftpl_starttime), callcounter); */
if (((ft_start_after_secs != -1) && (tmp_ts.tv_sec < ft_start_after_secs))
|| ((ft_stop_after_secs != -1) && (tmp_ts.tv_sec >= ft_stop_after_secs))
|| ((ft_start_after_ncalls != -1) && (callcounter < ft_start_after_ncalls))
|| ((ft_stop_after_ncalls != -1) && (callcounter >= ft_stop_after_ncalls)))
{
ret = 0;
goto abort;
}
/* fprintf(stderr, "(libfaketime limits -> runtime: %lu, callcounter: %lu continues\n", (*time_tptr - ftpl_starttime), callcounter); */
}
if (spawnsupport)
{
/* check whether we should spawn an external command */
if (spawned == 0)
{ /* exec external command once only */
if (((tmp_ts.tv_sec == ft_spawn_secs) || (callcounter == ft_spawn_ncalls)) && (spawned == 0))
{
spawned = 1;
(void) (system(ft_spawn_target) + 1);
}
}
}
}
struct timespec current_ts;
DONT_FAKE_TIME((*real_clock_gettime)(CLOCK_REALTIME, ¤t_ts));
if (last_data_fetch > 0)
{
if ((current_ts.tv_sec - last_data_fetch) > cache_duration)
{
cache_expired = 1;
}
else
{
cache_expired = 0;
}
}
if (cache_enabled == 0)
{
cache_expired = 1;
}
if (force_cache_expiration != 0)
{
cache_expired = 1;
force_cache_expiration = 0;
}
if (cache_expired == 1)
{
static char user_faked_time[BUFFERLEN]; /* changed to static for caching in v0.6 */
/* initialize with default or env. variable */
char *tmp_env;
/* Can be enabled for testing ...
fprintf(stderr, "***************++ Cache expired ++**************\n");
*/
if (NULL != (tmp_env = getenv("FAKETIME")))
{
strncpy(user_faked_time, tmp_env, BUFFERLEN - 1);
user_faked_time[BUFFERLEN - 1] = 0;
}
else
{
snprintf(user_faked_time, BUFFERLEN, "+0");
}
last_data_fetch = current_ts.tv_sec;
/* fake time supplied as environment variable? */
if (parse_config_file)
{
if (read_config_file() == 0) parse_ft_string(user_faked_time);
} /* read fake time from file */
else
{
parse_ft_string(user_faked_time);
}
/* read monotonic faketime setting from envar */
get_fake_monotonic_setting(&fake_monotonic_clock);
} /* cache had expired */
if (infile_set)
{
if (load_time(tp))
{
ret = 0;
goto abort;
}
}
/* check whether the user gave us an absolute time to fake */
switch (ft_mode)
{
case FT_FREEZE: /* a specified time */
if (user_faked_time_set)
{
*tp = user_faked_time_timespec;
}
break;
case FT_START_AT: /* User-specified offset */
if (user_per_tick_inc_set)
{
/* increment time with every time() call */
next_time(tp, &user_per_tick_inc);
}
else
{
/* Speed-up / slow-down contributed by Karl Chen in v0.8 */
struct timespec tdiff, timeadj;
switch (clk_id)
{
case CLOCK_REALTIME:
#ifdef CLOCK_REALTIME_COARSE
case CLOCK_REALTIME_COARSE:
#endif
timespecsub(tp, &ftpl_starttime.real, &tdiff);
break;
case CLOCK_MONOTONIC:
#ifdef CLOCK_MONOTONIC_COARSE
case CLOCK_MONOTONIC_COARSE:
#endif
timespecsub(tp, &ftpl_starttime.mon, &tdiff);
break;
case CLOCK_MONOTONIC_RAW:
timespecsub(tp, &ftpl_starttime.mon_raw, &tdiff);
break;
#ifdef CLOCK_BOOTTIME
case CLOCK_BOOTTIME:
timespecsub(tp, &ftpl_starttime.boot, &tdiff);
break;
#endif
default:
timespecsub(tp, &ftpl_starttime.real, &tdiff);
break;
} // end of switch (clk_id)
if (user_rate_set)
{
timespecmul(&tdiff, user_rate, &timeadj);
}
else
{
timeadj = tdiff;
}
timespecadd(&user_faked_time_timespec, &timeadj, tp);
}
break;
default:
ret = -1;
goto abort;
} // end of switch(ft_mode)
abort:
#ifdef PTHREAD_SINGLETHREADED_TIME
pthread_cleanup_pop(1);
#endif
// came here via goto abort?
if (ret != INT_MAX) return ret;
save_time(tp);
/* Cache this most recent real and faked time we encountered */
if (clk_id == CLOCK_REALTIME)
{
ftpl_timecache.real.tv_sec = tp_save.tv_sec;
ftpl_timecache.real.tv_nsec = tp_save.tv_nsec;
ftpl_faketimecache.real.tv_sec = tp->tv_sec;
ftpl_faketimecache.real.tv_nsec = tp->tv_nsec;
}
else if (clk_id == CLOCK_MONOTONIC)
{
ftpl_timecache.mon.tv_sec = tp_save.tv_sec;
ftpl_timecache.mon.tv_nsec = tp_save.tv_nsec;
ftpl_faketimecache.mon.tv_sec = tp->tv_sec;
ftpl_faketimecache.mon.tv_nsec = tp->tv_nsec;
}
else if (clk_id == CLOCK_MONOTONIC_RAW)
{
ftpl_timecache.mon_raw.tv_sec = tp_save.tv_sec;
ftpl_timecache.mon_raw.tv_nsec = tp_save.tv_nsec;
ftpl_faketimecache.mon_raw.tv_sec = tp->tv_sec;
ftpl_faketimecache.mon_raw.tv_nsec = tp->tv_nsec;
}
#ifdef CLOCK_BOOTTIME
else if (clk_id == CLOCK_BOOTTIME)
{
ftpl_timecache.boot.tv_sec = tp_save.tv_sec;
ftpl_timecache.boot.tv_nsec = tp_save.tv_nsec;
ftpl_faketimecache.boot.tv_sec = tp->tv_sec;
ftpl_faketimecache.boot.tv_nsec = tp->tv_nsec;
}
#endif
return 0;
}
int fake_gettimeofday(struct timeval *tv)
{
struct timespec ts;
int ret;
ts.tv_sec = tv->tv_sec;
ts.tv_nsec = tv->tv_usec * 1000 + ftpl_starttime.real.tv_nsec % 1000;
ret = fake_clock_gettime(CLOCK_REALTIME, &ts);
tv->tv_sec = ts.tv_sec;
tv->tv_usec =ts.tv_nsec / 1000;
return ret;
}
/*
* =======================================================================
* Faked system functions: Apple Mac OS X specific === FAKE(OSX)
* =======================================================================
*/
#ifdef __APPLEOSX__
/*
* clock_gettime implementation for __APPLE__
* @note It always behave like being called with CLOCK_REALTIME.
*/
static int apple_clock_gettime(clockid_t clk_id, struct timespec *tp)
{
int result;
mach_timespec_t cur_timeclockid_t;
(void) clk_id; /* unused */
if (!CHECK_MISSING_REAL(clock_get_time)) return -1;
DONT_FAKE_TIME(result = (*real_clock_get_time)(clock_serv_real, &cur_timeclockid_t));
tp->tv_sec = cur_timeclockid_t.tv_sec;
tp->tv_nsec = cur_timeclockid_t.tv_nsec;
return result;
}
int clock_get_time(clock_serv_t clock_serv, mach_timespec_t *cur_timeclockid_t)
{
int result;
struct timespec ts;
/*
* Initialize our result with the real current time from CALENDAR_CLOCK.
* This is a bit of cheating, but we don't keep track of obtained clock
* services.
*/
DONT_FAKE_TIME(result = (*real_clock_gettime)(CLOCK_REALTIME, &ts));
if (result == -1) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
result = fake_clock_gettime(CLOCK_REALTIME, &ts);
cur_timeclockid_t->tv_sec = ts.tv_sec;
cur_timeclockid_t->tv_nsec = ts.tv_nsec;
/* return the result to the caller */
return result;
}
#endif
/*
* =======================================================================
* Faked system-internal functions === FAKE(INT)
* =======================================================================
*/
#ifdef FAKE_INTERNAL_CALLS
int __gettimeofday(struct timeval *tv, void *tz)
{
int result;
/* sanity check */
if (tv == NULL)
{
return -1;
}
/* Check whether we've got a pointer to the real ftime() function yet */
if (!CHECK_MISSING_REAL(__gettimeofday)) return -1;
/* initialize our result with the real current time */
DONT_FAKE_TIME(result = (*real___gettimeofday)(tv, tz));
if (result == -1) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
result = fake_gettimeofday(tv);
/* return the result to the caller */
return result;
}
int __clock_gettime(clockid_t clk_id, struct timespec *tp)
{
int result;
/* sanity check */
if (tp == NULL)
{
return -1;
}
if (!CHECK_MISSING_REAL(__clock_gettime)) return -1;
/* initialize our result with the real current time */
DONT_FAKE_TIME(result = (*real___clock_gettime)(clk_id, tp));
if (result == -1) return result; /* original function failed */
/* pass the real current time to our faking version, overwriting it */
if (fake_monotonic_clock || (clk_id != CLOCK_MONOTONIC && clk_id != CLOCK_MONOTONIC_RAW
#ifdef CLOCK_MONOTONIC_COARSE
&& clk_id != CLOCK_MONOTONIC_COARSE
#endif
#ifdef CLOCK_BOOTTIME
&& clk_id != CLOCK_BOOTTIME
#endif
))
{
result = fake_clock_gettime(clk_id, tp);
}
/* return the result to the caller */
return result;
}
time_t __time(time_t *time_tptr)
{
struct timespec tp;
time_t result;
DONT_FAKE_TIME(result = (*real_clock_gettime)(CLOCK_REALTIME, &tp));
if (result == -1) return -1;
/* pass the real current time to our faking version, overwriting it */
(void)fake_clock_gettime(CLOCK_REALTIME, &tp);
if (time_tptr != NULL)
{
*time_tptr = tp.tv_sec;
}
return tp.tv_sec;
}
int __ftime(struct timeb *tb)
{
struct timespec tp;
int result;
/* sanity check */
if (tb == NULL)
return 0; /* ftime() always returns 0, see manpage */
/* Check whether we've got a pointer to the real ftime() function yet */
if (!CHECK_MISSING_REAL(__ftime)) return 0;
/* initialize our TZ result with the real current time */
DONT_FAKE_TIME(result = (*real___ftime)(tb));
if (result == -1)
{
return result;
}
DONT_FAKE_TIME(result = (*real_clock_gettime)(CLOCK_REALTIME, &tp));
if (result == -1) return -1;
/* pass the real current time to our faking version, overwriting it */
(void)fake_clock_gettime(CLOCK_REALTIME, &tp);
tb->time = tp.tv_sec;
tb->millitm = tp.tv_nsec / 1000000;
/* return the result to the caller */
return result; /* will always be 0 (see manpage) */
}
#endif
/*
* =======================================================================
* Faked pthread_cond_timedwait === FAKE(pthread)
* =======================================================================
*/
/* pthread_cond_timedwait
The specified absolute time in pthread_cond_timedwait is directly
passed to the kernel via the futex syscall. The kernel, however,
does not know about the fake time. In 99.9% of cases, the time
until this function should wait is calculated by an application
relatively to the current time, which has been faked in the
application. Hence, we should convert the waiting time back to real
time.
pthread_cond_timedwait in GLIBC_2_2_5 only supports
CLOCK_REALTIME. Since the init and destroy functions are not
redefined for GLIBC_2_2_5, a corresponding cond will never be
added to monotonic_conds and hence the correct branch will
always be taken.
*/
#ifdef FAKE_PTHREAD
typedef enum {FT_COMPAT_GLIBC_2_2_5, FT_COMPAT_GLIBC_2_3_2} ft_lib_compat_pthread;
struct pthread_cond_monotonic {
pthread_cond_t *ptr;
UT_hash_handle hh;
};
static struct pthread_cond_monotonic *monotonic_conds = NULL;
int pthread_cond_init_232(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr)
{
clockid_t clock_id;
int result;
if (!initialized)
{
ftpl_init();
}
if (!CHECK_MISSING_REAL(pthread_cond_init_232)) return -1;
result = real_pthread_cond_init_232(cond, attr);
if (result != 0 || attr == NULL)
return result;
pthread_condattr_getclock(attr, &clock_id);
if (clock_id == CLOCK_MONOTONIC) {
struct pthread_cond_monotonic *e = (struct pthread_cond_monotonic*)malloc(sizeof(struct pthread_cond_monotonic));
e->ptr = cond;
if (pthread_rwlock_wrlock(&monotonic_conds_lock) != 0) {
fprintf(stderr,"can't acquire write monotonic_conds_lock\n");
exit(-1);
}
HASH_ADD_PTR(monotonic_conds, ptr, e);
pthread_rwlock_unlock(&monotonic_conds_lock);
}
return result;
}
int pthread_cond_destroy_232(pthread_cond_t *cond)
{
struct pthread_cond_monotonic* e;
if (pthread_rwlock_wrlock(&monotonic_conds_lock) != 0) {
fprintf(stderr,"can't acquire write monotonic_conds_lock\n");
exit(-1);
}
HASH_FIND_PTR(monotonic_conds, &cond, e);
if (e) {
HASH_DEL(monotonic_conds, e);
free(e);
}
pthread_rwlock_unlock(&monotonic_conds_lock);
return real_pthread_cond_destroy_232(cond);
}
//where init in pthread methods????
int pthread_cond_timedwait_common(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime, ft_lib_compat_pthread compat)
{
struct timespec tp, tdiff_actual, realtime, faketime;
struct timespec *tf = NULL;
struct pthread_cond_monotonic* e;
char *tmp_env;
int wait_ms;
clockid_t clk_id;
int result = 0;
if (abstime != NULL)
{
if (pthread_rwlock_rdlock(&monotonic_conds_lock) != 0) {
fprintf(stderr,"can't acquire read monotonic_conds_lock\n");
exit(-1);
}
HASH_FIND_PTR(monotonic_conds, &cond, e);
pthread_rwlock_unlock(&monotonic_conds_lock);
if (e != NULL)
clk_id = CLOCK_MONOTONIC;
else
clk_id = CLOCK_REALTIME;
DONT_FAKE_TIME(result = (*real_clock_gettime)(clk_id, &realtime));
if (result == -1)
{
return EINVAL;
}
faketime = realtime;
(void)fake_clock_gettime(clk_id, &faketime);
if ((tmp_env = getenv("FAKETIME_WAIT_MS")) != NULL)
{
wait_ms = atol(tmp_env);
DONT_FAKE_TIME(result = (*real_clock_gettime)(clk_id, &realtime));
if (result == -1)
{
return EINVAL;
}
tdiff_actual.tv_sec = wait_ms / 1000;
tdiff_actual.tv_nsec = (wait_ms % 1000) * 1000000;
timespecadd(&realtime, &tdiff_actual, &tp);
tf = &tp;
}
else
{
timespecsub(abstime, &faketime, &tp);
if (user_rate_set)
{
timespecmul(&tp, 1.0 / user_rate, &tdiff_actual);
}
else
{
tdiff_actual = tp;
}
}
/* For CLOCK_MONOTONIC, pthread_cond_timedwait uses clock_gettime
internally to calculate the appropriate duration for the
waiting time. This already uses the faked functions, hence, the
fake time needs to be passed to pthread_cond_timedwait for
CLOCK_MONOTONIC. */
#ifndef __ARM_ARCH
#ifndef FORCE_MONOTONIC_FIX
if (clk_id == CLOCK_MONOTONIC)
timespecadd(&faketime, &tdiff_actual, &tp);
else
#endif
#endif
timespecadd(&realtime, &tdiff_actual, &tp);
tf = &tp;
}
switch (compat) {
case FT_COMPAT_GLIBC_2_3_2:
result = real_pthread_cond_timedwait_232(cond, mutex, tf);
break;
case FT_COMPAT_GLIBC_2_2_5:
result = real_pthread_cond_timedwait_225(cond, mutex, tf);
break;
}
return result;
}
int pthread_cond_timedwait_225(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
{
return pthread_cond_timedwait_common(cond, mutex, abstime, FT_COMPAT_GLIBC_2_2_5);
}
int pthread_cond_timedwait_232(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
{
return pthread_cond_timedwait_common(cond, mutex, abstime, FT_COMPAT_GLIBC_2_3_2);
}
__asm__(".symver pthread_cond_timedwait_225, pthread_cond_timedwait@GLIBC_2.2.5");
#if defined __ARM_ARCH || defined FORCE_PTHREAD_NONVER
__asm__(".symver pthread_cond_timedwait_232, pthread_cond_timedwait@@");
__asm__(".symver pthread_cond_init_232, pthread_cond_init@@");
__asm__(".symver pthread_cond_destroy_232, pthread_cond_destroy@@");
#else
__asm__(".symver pthread_cond_timedwait_232, pthread_cond_timedwait@@GLIBC_2.3.2");
__asm__(".symver pthread_cond_init_232, pthread_cond_init@@GLIBC_2.3.2");
__asm__(".symver pthread_cond_destroy_232, pthread_cond_destroy@@GLIBC_2.3.2");
#endif
#endif
/*
* Intercept calls to time-setting functions if compiled with FAKE_SETTIME set.
* Based on suggestion and prototype by @ojura, see https://github.com/wolfcw/libfaketime/issues/179
*/
#ifdef FAKE_SETTIME
#ifdef MACOS_DYLD_INTERPOSE
int macos_clock_settime(clockid_t clk_id, const struct timespec *tp) {
#else
int clock_settime(clockid_t clk_id, const struct timespec *tp) {
#endif
/* only CLOCK_REALTIME can be set */
if (clk_id != CLOCK_REALTIME) {
errno = EPERM;
return -1;
}
/* sanity check for the pointer */
if (tp == NULL) {
errno = EFAULT;
return -1;
}
/* When setting the FAKETIME environment variable to the new timestamp,
we do not have to care about 'x' or 'i' modifiers given previously,
as they are not erased when parsing them. */
struct timespec current_time;
#ifdef MACOS_DYLD_INTERPOSE
DONT_FAKE_TIME(macos_clock_gettime(clk_id, ¤t_time))
#else
DONT_FAKE_TIME(clock_gettime(clk_id, ¤t_time))
#endif
;
time_t sec_diff = tp->tv_sec - current_time.tv_sec;
long nsec_diff = tp->tv_nsec - current_time.tv_nsec;
char newenv_string[256];
double offset = (double) sec_diff;
offset += (double) nsec_diff/SEC_TO_nSEC;
snprintf(newenv_string, 255, "%+f", offset);
parse_config_file = false; /* #247: make sure environment takes precedence */
setenv("FAKETIME", newenv_string, 1);
force_cache_expiration = 1; /* make sure it becomes effective immediately */
/* If FAKETIME_TIMESTAMP_FILE was given in environment,
* and if FAKETIME_UPDATE_TIMESTAMP_FILE=1, then update it.
* This allows other process instances to share the same time. */
if ( (getenv("FAKETIME_TIMESTAMP_FILE") != NULL)
&& (*getenv("FAKETIME_TIMESTAMP_FILE") != '\0')
&& (getenv("FAKETIME_UPDATE_TIMESTAMP_FILE") != NULL)
&& (strcmp(getenv("FAKETIME_UPDATE_TIMESTAMP_FILE"), "1") == 0))
{
const char *error = NULL;
FILE *envfile;
static char custom_filename[BUFSIZ];
(void) snprintf(custom_filename, BUFSIZ, "%s", getenv("FAKETIME_TIMESTAMP_FILE"));
if ((envfile = fopen(custom_filename, "wt")) != NULL)
{
if (fprintf(envfile, "%+f\n", offset) < 0)
{
error = "to write to file";
}
if (fclose(envfile) != 0)
{
error = "to close file";
}
}
else
{
error = "to open file";
}
if (error)
{
fprintf(stderr, "libfaketime: In clock_settime(), failed to "
"%s while updating FAKETIME_TIMESTAMP_FILE (`%s'): %s\n",
error, getenv("FAKETIME_TIMESTAMP_FILE"), strerror(errno));
}
}
return 0;
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_settimeofday(const struct timeval *tv, void *tz)
#else
int settimeofday(const struct timeval *tv, void *tz)
#endif
{
/* The use of timezone *tz is obsolete and simply ignored here. */
if (tz == NULL) tz = NULL;
if (tv == NULL)
{
errno = EFAULT;
return -1;
}
else
{
struct timespec tp;
tp.tv_sec = tv->tv_sec;
tp.tv_nsec = tv->tv_usec * 1000;
#ifdef MACOS_DYLD_INTERPOSE
macos_clock_settime(CLOCK_REALTIME, &tp);
#else
clock_settime(CLOCK_REALTIME, &tp);
#endif
}
return 0;
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_adjtime (const struct timeval *delta, struct timeval *olddelta)
#else
int adjtime (const struct timeval *delta, struct timeval *olddelta)
#endif
{
/* Always signal true full success when olddelta is requested. */
if (olddelta != NULL)
{
olddelta->tv_sec = 0;
olddelta->tv_usec = 0;
}
if (delta != NULL)
{
struct timespec tp;
#ifdef MACOS_DYLD_INTERPOSE
macos_clock_gettime(CLOCK_REALTIME, &tp);
#else
clock_gettime(CLOCK_REALTIME, &tp);
#endif
tp.tv_sec += delta->tv_sec;
tp.tv_nsec += delta->tv_usec * 1000;
/* This actually will make the clock jump instead of gradually
adjusting it, but we fulfill the caller's intention and an
additional thread just for the gradual changes does not seem
to be worth the effort presently. */
#ifdef MACOS_DYLD_INTERPOSE
clock_settime(CLOCK_REALTIME, &tp);
#else
clock_settime(CLOCK_REALTIME, &tp);
#endif
}
return 0;
}
#endif
#ifdef FAKE_RANDOM
/*
Local copy of
Middle Square Weyl Sequence Random Number Generator
Copyright (c) 2014-2020 Bernard Widynski
License: GNU GPL v3
see https://mswsrng.wixsite.com/rand
adapted to take the seed s as a parameter and return only a byte
*/
inline static uint32_t fakerandom_msws(uint64_t s) {
static uint64_t x = 0, w = 0;
x *= x; x += (w += s);
x = (x>>32) | (x<<32);
return (char) x & 0xFF;
}
/* return 0 if no FAKERANDOM_SEED was seen */
static int bypass_randomness(void* buf, size_t buflen) {
char *seedstring = getenv("FAKERANDOM_SEED");
char *b = buf;
if (seedstring != NULL) {
long long int seed = strtoll(seedstring, NULL, 0);
for (size_t i = 0; i < buflen; i++) {
b[i] = fakerandom_msws(seed);
}
return 1;
}
return 0;
}
ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) {
if (bypass_randomness(buf, buflen)) {
return buflen;
} else {
if (!initialized)
{
ftpl_init();
}
return real_getrandom(buf, buflen, flags);
}
}
#ifdef MACOS_DYLD_INTERPOSE
int macos_getentropy(void *buffer, size_t length) {
#else
int getentropy(void *buffer, size_t length) {
#endif
if (bypass_randomness(buffer, length)) {
return 0;
} else {
if (!initialized)
ftpl_init();
#ifdef MACOS_DYLD_INTERPOSE
return getentropy(buffer, length);
#else
return real_getentropy(buffer, length);
#endif
}
}
#endif
#ifdef FAKE_PID
#ifdef MACOS_DYLD_INTERPOSE
pid_t macos_getpid() {
#else
pid_t getpid() {
#endif
const char *pidstring = getenv("FAKETIME_FAKEPID");
if (pidstring != NULL) {
long int pid = strtol(pidstring, NULL, 0);
return (pid_t)(pid);
} else {
if (!initialized)
{
ftpl_init();
}
return real_getpid();
}
}
#endif
#ifdef INTERCEPT_SYSCALL
/* see https://github.com/wolfcw/libfaketime/issues/301 */
long syscall(long number, ...) {
va_list ap;
va_start(ap, number);
#ifdef FAKE_RANDOM
if (number == __NR_getrandom && getenv("FAKERANDOM_SEED")) {
void *buf;
size_t buflen;
unsigned int flags;
buf = va_arg(ap, void*);
buflen = va_arg(ap, size_t);
flags = va_arg(ap, unsigned int);
va_end(ap);
return getrandom(buf, buflen, flags);
}
#endif
// static int (*real_clock_gettime) (clockid_t clk_id, struct timespec *tp);
if (number == __NR_clock_gettime && getenv("FAKETIME")) {
clockid_t clk_id;
struct timespec *tp;
clk_id = va_arg(ap, clockid_t);
tp = va_arg(ap, struct timespec*);
va_end(ap);
return clock_gettime(clk_id, tp);
}
variadic_promotion_t a[syscall_max_args];
for (int i = 0; i < syscall_max_args; i++)
a[i] = va_arg(ap, variadic_promotion_t);
va_end(ap);
if (!initialized)
ftpl_init();
return real_syscall(number, a[0], a[1], a[2], a[3], a[4], a[5]);
}
#endif
#ifdef MACOS_DYLD_INTERPOSE
void do_macos_dyld_interpose(void) {
DYLD_INTERPOSE(macos_clock_gettime, clock_gettime);
DYLD_INTERPOSE(macos_gettimeofday, gettimeofday);
DYLD_INTERPOSE(macos_time, time);
DYLD_INTERPOSE(macos_ftime, ftime);
#ifdef FAKE_SLEEP
DYLD_INTERPOSE(macos_alarm, alarm);
DYLD_INTERPOSE(macos_sleep, sleep);
DYLD_INTERPOSE(macos_usleep, usleep);
DYLD_INTERPOSE(macos_nanosleep, nanosleep);
DYLD_INTERPOSE(macos_poll, poll);
#endif
DYLD_INTERPOSE(macos_timespec_get, timespec_get);
DYLD_INTERPOSE(macos_select, select);
#ifdef FAKE_RANDOM
DYLD_INTERPOSE(macos_getentropy, getentropy);
#endif
#ifdef FAKE_SETTIME
DYLD_INTERPOSE(macos_clock_settime, clock_settime);
DYLD_INTERPOSE(macos_settimeofday, settimeofday);
DYLD_INTERPOSE(macos_adjtime, adjtime);
#endif
#ifdef FAKE_PID
DYLD_INTERPOSE(macos_getpid, getpid);
#endif
}
#endif
/*
* Editor modelines
*
* Local variables:
* c-basic-offset: 2
* tab-width: 2
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=2 tabstop=2 expandtab:
* :indentSize=2:tabSize=2:noTabs=true:
*/
/* eof */
|