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
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Ensure 64-bit off_t for platforms where it matters
#ifdef _FILE_OFFSET_BITS
# undef _FILE_OFFSET_BITS
#endif
#define _FILE_OFFSET_BITS 64
#if defined(sun) || defined(__sun)
// According to https://bugs.python.org/issue1759169#msg82201, __EXTENSIONS__
// is the best way to enable modern POSIX APIs, such as posix_madvise(), on Solaris.
// (see also
// https://github.com/illumos/illumos-gate/blob/master/usr/src/uts/common/sys/mman.h)
# undef __EXTENSIONS__
# define __EXTENSIONS__
#endif
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/windows_compatibility.h" // IWYU pragma: keep
#include <algorithm>
#include <array>
#include <cerrno>
#include <climits>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <mutex>
#include <random>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h> // IWYU pragma: keep
// ----------------------------------------------------------------------
// file compatibility stuff
#ifdef _WIN32
# include <direct.h>
# include <io.h>
# include <share.h>
#else // POSIX-like platforms
# include <dirent.h>
#endif
#ifdef _WIN32
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/io/mman.h"
# undef Realloc
# undef Free
#else // POSIX-like platforms
# include <sys/mman.h>
# include <unistd.h>
#endif
// define max read/write count
#ifdef _WIN32
# define ARROW_MAX_IO_CHUNKSIZE INT32_MAX
#else
# ifdef __APPLE__
// due to macOS bug, we need to set read/write max
# define ARROW_MAX_IO_CHUNKSIZE INT32_MAX
# else
// see notes on Linux read/write manpage
# define ARROW_MAX_IO_CHUNKSIZE 0x7ffff000
# endif
#endif
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/buffer.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/result.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/atfork_internal.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/checked_cast.h"
#include "contrib/libs/apache/arrow_next/src/arrow/util/config.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/io_util.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/logging.h"
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/mutex.h"
// For filename conversion
#if defined(_WIN32)
#include "contrib/libs/apache/arrow_next/cpp/src/arrow/util/utf8.h"
#endif
#ifdef _WIN32
# include <psapi.h>
#elif __APPLE__
# include <mach/mach.h>
# include <sys/sysctl.h>
#elif __linux__
# include <sys/sysinfo.h>
# include <fstream>
#endif
#ifdef _WIN32
# include <windows.h>
#else
# include <dlfcn.h>
#endif
namespace arrow20::internal {
namespace {
template <typename CharT>
std::basic_string<CharT> ReplaceChars(std::basic_string<CharT> s, CharT find, CharT rep) {
if (find != rep) {
for (size_t i = 0; i < s.length(); ++i) {
if (s[i] == find) {
s[i] = rep;
}
}
}
return s;
}
Result<NativePathString> StringToNative(std::string_view s) {
#if _WIN32
return ::arrow20::util::UTF8ToWideString(s);
#else
return std::string(s);
#endif
}
#if _WIN32
Result<std::string> NativeToString(const NativePathString& ws) {
return ::arrow20::util::WideStringToUTF8(ws);
}
#endif
#if _WIN32
const wchar_t kNativeSep = L'\\';
const wchar_t kGenericSep = L'/';
const wchar_t* kAllSeps = L"\\/";
#else
const char kNativeSep = '/';
const char kGenericSep = '/';
const char* kAllSeps = "/";
#endif
NativePathString NativeSlashes(NativePathString s) {
return ReplaceChars(std::move(s), kGenericSep, kNativeSep);
}
NativePathString GenericSlashes(NativePathString s) {
return ReplaceChars(std::move(s), kNativeSep, kGenericSep);
}
NativePathString NativeParent(const NativePathString& s) {
auto last_sep = s.find_last_of(kAllSeps);
if (last_sep == s.length() - 1) {
// Last separator is a trailing separator, skip all trailing separators
// and try again
auto before_last_seps = s.find_last_not_of(kAllSeps);
if (before_last_seps == NativePathString::npos) {
// Only separators in path
return s;
}
last_sep = s.find_last_of(kAllSeps, before_last_seps);
}
if (last_sep == NativePathString::npos) {
// No (other) separator in path
return s;
}
// There may be multiple contiguous separators, skip all of them
auto before_last_seps = s.find_last_not_of(kAllSeps, last_sep);
if (before_last_seps == NativePathString::npos) {
// All separators are at start of string, keep them all
return s.substr(0, last_sep + 1);
} else {
return s.substr(0, before_last_seps + 1);
}
}
Status ValidatePath(std::string_view s) {
if (s.find_first_of('\0') != std::string::npos) {
return Status::Invalid("Embedded NUL char in path: '", s, "'");
}
return Status::OK();
}
} // namespace
std::string ErrnoMessage(int errnum) { return std::strerror(errnum); }
#if _WIN32
std::string WinErrorMessage(int errnum) {
constexpr DWORD max_n_chars = 1024;
WCHAR utf16_message[max_n_chars];
auto n_utf16_chars =
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
errnum, 0, utf16_message, max_n_chars, NULL);
if (n_utf16_chars == 0) {
// Fallback
std::stringstream ss;
ss << "Windows error #" << errnum;
return ss.str();
}
auto utf8_message_result =
arrow20::util::WideStringToUTF8(std::wstring(utf16_message, n_utf16_chars));
if (!utf8_message_result.ok()) {
std::stringstream ss;
ss << "Windows error #" << errnum;
ss << "; failed to convert error message to UTF-8: " << utf8_message_result.status();
return ss.str();
}
return *utf8_message_result;
}
#endif
namespace {
const char kErrnoDetailTypeId[] = "arrow20::ErrnoDetail";
class ErrnoDetail : public StatusDetail {
public:
explicit ErrnoDetail(int errnum) : errnum_(errnum) {}
const char* type_id() const override { return kErrnoDetailTypeId; }
std::string ToString() const override {
std::stringstream ss;
ss << "[errno " << errnum_ << "] " << ErrnoMessage(errnum_);
return ss.str();
}
int errnum() const { return errnum_; }
protected:
int errnum_;
};
#if _WIN32
const char kWinErrorDetailTypeId[] = "arrow20::WinErrorDetail";
// Map from a Windows error code to a `errno` value
//
// Most code in this function is taken from CPython's `PC/errmap.h`.
// Unlike CPython however, we return 0 for unknown / unsupported values.
int WinErrorToErrno(int winerror) {
// Unwrap FACILITY_WIN32 HRESULT errors.
if ((winerror & 0xFFFF0000) == 0x80070000) {
winerror &= 0x0000FFFF;
}
// Winsock error codes (10000-11999) are errno values.
if (winerror >= 10000 && winerror < 12000) {
switch (winerror) {
case WSAEINTR:
case WSAEBADF:
case WSAEACCES:
case WSAEFAULT:
case WSAEINVAL:
case WSAEMFILE:
// Winsock definitions of errno values. See WinSock2.h
return winerror - 10000;
default:
return winerror;
}
}
switch (winerror) {
case ERROR_FILE_NOT_FOUND: // 2
case ERROR_PATH_NOT_FOUND: // 3
case ERROR_INVALID_DRIVE: // 15
case ERROR_NO_MORE_FILES: // 18
case ERROR_BAD_NETPATH: // 53
case ERROR_BAD_NET_NAME: // 67
case ERROR_BAD_PATHNAME: // 161
case ERROR_FILENAME_EXCED_RANGE: // 206
return ENOENT;
case ERROR_BAD_ENVIRONMENT: // 10
return E2BIG;
case ERROR_BAD_FORMAT: // 11
case ERROR_INVALID_STARTING_CODESEG: // 188
case ERROR_INVALID_STACKSEG: // 189
case ERROR_INVALID_MODULETYPE: // 190
case ERROR_INVALID_EXE_SIGNATURE: // 191
case ERROR_EXE_MARKED_INVALID: // 192
case ERROR_BAD_EXE_FORMAT: // 193
case ERROR_ITERATED_DATA_EXCEEDS_64k: // 194
case ERROR_INVALID_MINALLOCSIZE: // 195
case ERROR_DYNLINK_FROM_INVALID_RING: // 196
case ERROR_IOPL_NOT_ENABLED: // 197
case ERROR_INVALID_SEGDPL: // 198
case ERROR_AUTODATASEG_EXCEEDS_64k: // 199
case ERROR_RING2SEG_MUST_BE_MOVABLE: // 200
case ERROR_RELOC_CHAIN_XEEDS_SEGLIM: // 201
case ERROR_INFLOOP_IN_RELOC_CHAIN: // 202
return ENOEXEC;
case ERROR_INVALID_HANDLE: // 6
case ERROR_INVALID_TARGET_HANDLE: // 114
case ERROR_DIRECT_ACCESS_HANDLE: // 130
return EBADF;
case ERROR_WAIT_NO_CHILDREN: // 128
case ERROR_CHILD_NOT_COMPLETE: // 129
return ECHILD;
case ERROR_NO_PROC_SLOTS: // 89
case ERROR_MAX_THRDS_REACHED: // 164
case ERROR_NESTING_NOT_ALLOWED: // 215
return EAGAIN;
case ERROR_ARENA_TRASHED: // 7
case ERROR_NOT_ENOUGH_MEMORY: // 8
case ERROR_INVALID_BLOCK: // 9
case ERROR_NOT_ENOUGH_QUOTA: // 1816
return ENOMEM;
case ERROR_ACCESS_DENIED: // 5
case ERROR_CURRENT_DIRECTORY: // 16
case ERROR_WRITE_PROTECT: // 19
case ERROR_BAD_UNIT: // 20
case ERROR_NOT_READY: // 21
case ERROR_BAD_COMMAND: // 22
case ERROR_CRC: // 23
case ERROR_BAD_LENGTH: // 24
case ERROR_SEEK: // 25
case ERROR_NOT_DOS_DISK: // 26
case ERROR_SECTOR_NOT_FOUND: // 27
case ERROR_OUT_OF_PAPER: // 28
case ERROR_WRITE_FAULT: // 29
case ERROR_READ_FAULT: // 30
case ERROR_GEN_FAILURE: // 31
case ERROR_SHARING_VIOLATION: // 32
case ERROR_LOCK_VIOLATION: // 33
case ERROR_WRONG_DISK: // 34
case ERROR_SHARING_BUFFER_EXCEEDED: // 36
case ERROR_NETWORK_ACCESS_DENIED: // 65
case ERROR_CANNOT_MAKE: // 82
case ERROR_FAIL_I24: // 83
case ERROR_DRIVE_LOCKED: // 108
case ERROR_SEEK_ON_DEVICE: // 132
case ERROR_NOT_LOCKED: // 158
case ERROR_LOCK_FAILED: // 167
case 35: // 35 (undefined)
return EACCES;
case ERROR_FILE_EXISTS: // 80
case ERROR_ALREADY_EXISTS: // 183
return EEXIST;
case ERROR_NOT_SAME_DEVICE: // 17
return EXDEV;
case ERROR_DIRECTORY: // 267 (bpo-12802)
return ENOTDIR;
case ERROR_TOO_MANY_OPEN_FILES: // 4
return EMFILE;
case ERROR_DISK_FULL: // 112
return ENOSPC;
case ERROR_BROKEN_PIPE: // 109
case ERROR_NO_DATA: // 232 (bpo-13063)
return EPIPE;
case ERROR_DIR_NOT_EMPTY: // 145
return ENOTEMPTY;
case ERROR_NO_UNICODE_TRANSLATION: // 1113
return EILSEQ;
case ERROR_INVALID_FUNCTION: // 1
case ERROR_INVALID_ACCESS: // 12
case ERROR_INVALID_DATA: // 13
case ERROR_INVALID_PARAMETER: // 87
case ERROR_NEGATIVE_SEEK: // 131
return EINVAL;
default:
return 0;
}
}
class WinErrorDetail : public StatusDetail {
public:
explicit WinErrorDetail(int errnum) : errnum_(errnum) {}
const char* type_id() const override { return kWinErrorDetailTypeId; }
std::string ToString() const override {
std::stringstream ss;
ss << "[Windows error " << errnum_ << "] " << WinErrorMessage(errnum_);
return ss.str();
}
int errnum() const { return errnum_; }
int equivalent_errno() const { return WinErrorToErrno(errnum_); }
protected:
int errnum_;
};
#endif
const char kSignalDetailTypeId[] = "arrow20::SignalDetail";
class SignalDetail : public StatusDetail {
public:
explicit SignalDetail(int signum) : signum_(signum) {}
const char* type_id() const override { return kSignalDetailTypeId; }
std::string ToString() const override {
std::stringstream ss;
ss << "received signal " << signum_;
return ss.str();
}
int signum() const { return signum_; }
protected:
int signum_;
};
} // namespace
std::shared_ptr<StatusDetail> StatusDetailFromErrno(int errnum) {
if (!errnum) {
return nullptr;
}
return std::make_shared<ErrnoDetail>(errnum);
}
std::optional<int> ErrnoFromStatusDetail(const StatusDetail& detail) {
if (detail.type_id() == kErrnoDetailTypeId) {
return checked_cast<const ErrnoDetail&>(detail).errnum();
}
return std::nullopt;
}
#if _WIN32
std::shared_ptr<StatusDetail> StatusDetailFromWinError(int errnum) {
if (!errnum) {
return nullptr;
}
return std::make_shared<WinErrorDetail>(errnum);
}
#endif
std::shared_ptr<StatusDetail> StatusDetailFromSignal(int signum) {
return std::make_shared<SignalDetail>(signum);
}
int ErrnoFromStatus(const Status& status) {
const auto detail = status.detail();
if (detail != nullptr) {
if (detail->type_id() == kErrnoDetailTypeId) {
return checked_cast<const ErrnoDetail&>(*detail).errnum();
}
#if _WIN32
if (detail->type_id() == kWinErrorDetailTypeId) {
return checked_cast<const WinErrorDetail&>(*detail).equivalent_errno();
}
#endif
}
return 0;
}
int WinErrorFromStatus(const Status& status) {
#if _WIN32
const auto detail = status.detail();
if (detail != nullptr && detail->type_id() == kWinErrorDetailTypeId) {
return checked_cast<const WinErrorDetail&>(*detail).errnum();
}
#endif
return 0;
}
int SignalFromStatus(const Status& status) {
const auto detail = status.detail();
if (detail != nullptr && detail->type_id() == kSignalDetailTypeId) {
return checked_cast<const SignalDetail&>(*detail).signum();
}
return 0;
}
namespace {
Result<NativePathString> NativeReal(const NativePathString& path) {
#if _WIN32
std::array<wchar_t, _MAX_PATH> resolved = {};
if (_wfullpath(const_cast<wchar_t*>(path.c_str()), resolved.data(), resolved.size()) ==
nullptr) {
return IOErrorFromWinError(errno, "Failed to resolve real path");
}
#else
std::array<char, PATH_MAX + 1> resolved;
if (realpath(path.c_str(), resolved.data()) == nullptr) {
return IOErrorFromErrno(errno, "Failed to resolve real path");
}
#endif
return NativePathString{resolved.data()};
}
} // namespace
//
// PlatformFilename implementation
//
struct PlatformFilename::Impl {
Impl() = default;
explicit Impl(NativePathString p) : native_(NativeSlashes(std::move(p))) {}
NativePathString native_;
// '/'-separated
NativePathString generic() const { return GenericSlashes(native_); }
};
PlatformFilename::PlatformFilename() : impl_(new Impl{}) {}
PlatformFilename::~PlatformFilename() {}
PlatformFilename::PlatformFilename(Impl impl) : impl_(new Impl(std::move(impl))) {}
PlatformFilename::PlatformFilename(const PlatformFilename& other)
: PlatformFilename(Impl{other.impl_->native_}) {}
PlatformFilename::PlatformFilename(PlatformFilename&& other)
: impl_(std::move(other.impl_)) {}
PlatformFilename& PlatformFilename::operator=(const PlatformFilename& other) {
this->impl_.reset(new Impl{other.impl_->native_});
return *this;
}
PlatformFilename& PlatformFilename::operator=(PlatformFilename&& other) {
this->impl_ = std::move(other.impl_);
return *this;
}
PlatformFilename::PlatformFilename(NativePathString path)
: PlatformFilename(Impl{std::move(path)}) {}
PlatformFilename::PlatformFilename(const NativePathString::value_type* path)
: PlatformFilename(NativePathString(path)) {}
bool PlatformFilename::operator==(const PlatformFilename& other) const {
return impl_->native_ == other.impl_->native_;
}
bool PlatformFilename::operator!=(const PlatformFilename& other) const {
return impl_->native_ != other.impl_->native_;
}
const NativePathString& PlatformFilename::ToNative() const { return impl_->native_; }
std::string PlatformFilename::ToString() const {
#if _WIN32
auto result = NativeToString(impl_->generic());
if (!result.ok()) {
std::stringstream ss;
ss << "<Unrepresentable filename: " << result.status().ToString() << ">";
return ss.str();
}
return *std::move(result);
#else
return impl_->generic();
#endif
}
PlatformFilename PlatformFilename::Parent() const {
return PlatformFilename(NativeParent(ToNative()));
}
Result<PlatformFilename> PlatformFilename::Real() const {
ARROW_ASSIGN_OR_RAISE(auto real, NativeReal(ToNative()));
return PlatformFilename(std::move(real));
}
Result<PlatformFilename> PlatformFilename::FromString(std::string_view file_name) {
RETURN_NOT_OK(ValidatePath(file_name));
ARROW_ASSIGN_OR_RAISE(auto ns, StringToNative(file_name));
return PlatformFilename(std::move(ns));
}
PlatformFilename PlatformFilename::Join(const PlatformFilename& child) const {
if (impl_->native_.empty() || impl_->native_.back() == kNativeSep) {
return PlatformFilename(Impl{impl_->native_ + child.impl_->native_});
} else {
return PlatformFilename(Impl{impl_->native_ + kNativeSep + child.impl_->native_});
}
}
Result<PlatformFilename> PlatformFilename::Join(std::string_view child_name) const {
ARROW_ASSIGN_OR_RAISE(auto child,
PlatformFilename::FromString(std::string(child_name)));
return Join(child);
}
//
// Filesystem access routines
//
namespace {
Result<bool> DoCreateDir(const PlatformFilename& dir_path, bool create_parents) {
#ifdef _WIN32
const auto s = dir_path.ToNative().c_str();
if (CreateDirectoryW(s, nullptr)) {
return true;
}
int errnum = GetLastError();
if (errnum == ERROR_ALREADY_EXISTS) {
const auto attrs = GetFileAttributesW(s);
if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
// Note we propagate the original error, not the GetFileAttributesW() error
return IOErrorFromWinError(ERROR_ALREADY_EXISTS, "Cannot create directory '",
dir_path.ToString(), "': non-directory entry exists");
}
return false;
}
if (create_parents && errnum == ERROR_PATH_NOT_FOUND) {
auto parent_path = dir_path.Parent();
if (parent_path != dir_path) {
RETURN_NOT_OK(DoCreateDir(parent_path, create_parents));
return DoCreateDir(dir_path, false); // Retry
}
}
return IOErrorFromWinError(GetLastError(), "Cannot create directory '",
dir_path.ToString(), "'");
#else
const auto s = dir_path.ToNative().c_str();
if (mkdir(s, S_IRWXU | S_IRWXG | S_IRWXO) == 0) {
return true;
}
if (errno == EEXIST) {
struct stat st;
if (stat(s, &st) || !S_ISDIR(st.st_mode)) {
// Note we propagate the original errno, not the stat() errno
return IOErrorFromErrno(EEXIST, "Cannot create directory '", dir_path.ToString(),
"': non-directory entry exists");
}
return false;
}
if (create_parents && errno == ENOENT) {
auto parent_path = dir_path.Parent();
if (parent_path != dir_path) {
RETURN_NOT_OK(DoCreateDir(parent_path, create_parents));
return DoCreateDir(dir_path, false); // Retry
}
}
return IOErrorFromErrno(errno, "Cannot create directory '", dir_path.ToString(), "'");
#endif
}
} // namespace
Result<bool> CreateDir(const PlatformFilename& dir_path) {
return DoCreateDir(dir_path, false);
}
Result<bool> CreateDirTree(const PlatformFilename& dir_path) {
return DoCreateDir(dir_path, true);
}
#ifdef _WIN32
namespace {
void FindHandleDeleter(HANDLE* handle) {
if (!FindClose(*handle)) {
ARROW_LOG(WARNING) << "Cannot close directory handle: "
<< WinErrorMessage(GetLastError());
}
}
std::wstring PathWithoutTrailingSlash(const PlatformFilename& fn) {
std::wstring path = fn.ToNative();
while (!path.empty() && path.back() == kNativeSep) {
path.pop_back();
}
return path;
}
Result<std::vector<WIN32_FIND_DATAW>> ListDirInternal(const PlatformFilename& dir_path) {
WIN32_FIND_DATAW find_data;
std::wstring pattern = PathWithoutTrailingSlash(dir_path) + L"\\*.*";
HANDLE handle = FindFirstFileW(pattern.c_str(), &find_data);
if (handle == INVALID_HANDLE_VALUE) {
return IOErrorFromWinError(GetLastError(), "Cannot list directory '",
dir_path.ToString(), "'");
}
std::unique_ptr<HANDLE, decltype(&FindHandleDeleter)> handle_guard(&handle,
FindHandleDeleter);
std::vector<WIN32_FIND_DATAW> results;
do {
// Skip "." and ".."
if (find_data.cFileName[0] == L'.') {
if (find_data.cFileName[1] == L'\0' ||
(find_data.cFileName[1] == L'.' && find_data.cFileName[2] == L'\0')) {
continue;
}
}
results.push_back(find_data);
} while (FindNextFileW(handle, &find_data));
int errnum = GetLastError();
if (errnum != ERROR_NO_MORE_FILES) {
return IOErrorFromWinError(GetLastError(), "Cannot list directory '",
dir_path.ToString(), "'");
}
return results;
}
Status FindOneFile(const PlatformFilename& fn, WIN32_FIND_DATAW* find_data,
bool* exists = nullptr) {
HANDLE handle = FindFirstFileW(PathWithoutTrailingSlash(fn).c_str(), find_data);
if (handle == INVALID_HANDLE_VALUE) {
int errnum = GetLastError();
if (exists == nullptr ||
(errnum != ERROR_PATH_NOT_FOUND && errnum != ERROR_FILE_NOT_FOUND)) {
return IOErrorFromWinError(GetLastError(), "Cannot get information for path '",
fn.ToString(), "'");
}
*exists = false;
} else {
if (exists != nullptr) {
*exists = true;
}
FindHandleDeleter(&handle);
}
return Status::OK();
}
} // namespace
Result<std::vector<PlatformFilename>> ListDir(const PlatformFilename& dir_path) {
ARROW_ASSIGN_OR_RAISE(auto entries, ListDirInternal(dir_path));
std::vector<PlatformFilename> results;
results.reserve(entries.size());
for (const auto& entry : entries) {
results.emplace_back(std::wstring(entry.cFileName));
}
return results;
}
#else
Result<std::vector<PlatformFilename>> ListDir(const PlatformFilename& dir_path) {
DIR* dir = opendir(dir_path.ToNative().c_str());
if (dir == nullptr) {
return IOErrorFromErrno(errno, "Cannot list directory '", dir_path.ToString(), "'");
}
auto dir_deleter = [](DIR* dir) -> void {
if (closedir(dir) != 0) {
ARROW_LOG(WARNING) << "Cannot close directory handle: " << ErrnoMessage(errno);
}
};
std::unique_ptr<DIR, decltype(dir_deleter)> dir_guard(dir, dir_deleter);
std::vector<PlatformFilename> results;
errno = 0;
struct dirent* entry = readdir(dir);
while (entry != nullptr) {
std::string path = entry->d_name;
if (path != "." && path != "..") {
results.emplace_back(std::move(path));
}
entry = readdir(dir);
}
if (errno != 0) {
return IOErrorFromErrno(errno, "Cannot list directory '", dir_path.ToString(), "'");
}
return results;
}
#endif
namespace {
#ifdef _WIN32
Status DeleteDirTreeInternal(const PlatformFilename& dir_path);
// Remove a directory entry that's always a directory
Status DeleteDirEntryDir(const PlatformFilename& path, const WIN32_FIND_DATAW& entry,
bool remove_top_dir = true) {
if ((entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {
// It's a directory that doesn't have a reparse point => recurse
RETURN_NOT_OK(DeleteDirTreeInternal(path));
}
if (remove_top_dir) {
// Remove now empty directory or reparse point (e.g. symlink to dir)
if (!RemoveDirectoryW(path.ToNative().c_str())) {
return IOErrorFromWinError(GetLastError(), "Cannot delete directory entry '",
path.ToString(), "': ");
}
}
return Status::OK();
}
Status DeleteDirEntry(const PlatformFilename& path, const WIN32_FIND_DATAW& entry) {
if ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
return DeleteDirEntryDir(path, entry);
}
// It's a non-directory entry, most likely a regular file
if (!DeleteFileW(path.ToNative().c_str())) {
return IOErrorFromWinError(GetLastError(), "Cannot delete file '", path.ToString(),
"': ");
}
return Status::OK();
}
Status DeleteDirTreeInternal(const PlatformFilename& dir_path) {
ARROW_ASSIGN_OR_RAISE(auto entries, ListDirInternal(dir_path));
for (const auto& entry : entries) {
PlatformFilename path = dir_path.Join(PlatformFilename(entry.cFileName));
RETURN_NOT_OK(DeleteDirEntry(path, entry));
}
return Status::OK();
}
Result<bool> DeleteDirContents(const PlatformFilename& dir_path, bool allow_not_found,
bool remove_top_dir) {
bool exists = true;
WIN32_FIND_DATAW entry;
if (allow_not_found) {
RETURN_NOT_OK(FindOneFile(dir_path, &entry, &exists));
} else {
// Will raise if dir_path does not exist
RETURN_NOT_OK(FindOneFile(dir_path, &entry));
}
if (exists) {
RETURN_NOT_OK(DeleteDirEntryDir(dir_path, entry, remove_top_dir));
}
return exists;
}
#else // POSIX
Status LinkStat(const PlatformFilename& path, struct stat* lst, bool* exists = nullptr) {
if (lstat(path.ToNative().c_str(), lst) != 0) {
if (exists == nullptr || (errno != ENOENT && errno != ENOTDIR && errno != ELOOP)) {
return IOErrorFromErrno(errno, "Cannot get information for path '", path.ToString(),
"'");
}
*exists = false;
} else if (exists != nullptr) {
*exists = true;
}
return Status::OK();
}
Status DeleteDirTreeInternal(const PlatformFilename& dir_path);
Status DeleteDirEntryDir(const PlatformFilename& path, const struct stat& lst,
bool remove_top_dir = true) {
if (!S_ISLNK(lst.st_mode)) {
// Not a symlink => delete contents recursively
DCHECK(S_ISDIR(lst.st_mode));
RETURN_NOT_OK(DeleteDirTreeInternal(path));
if (remove_top_dir && rmdir(path.ToNative().c_str()) != 0) {
return IOErrorFromErrno(errno, "Cannot delete directory entry '", path.ToString(),
"'");
}
} else {
// Remove symlink
if (remove_top_dir && unlink(path.ToNative().c_str()) != 0) {
return IOErrorFromErrno(errno, "Cannot delete directory entry '", path.ToString(),
"'");
}
}
return Status::OK();
}
Status DeleteDirEntry(const PlatformFilename& path, const struct stat& lst) {
if (S_ISDIR(lst.st_mode)) {
return DeleteDirEntryDir(path, lst);
}
if (unlink(path.ToNative().c_str()) != 0) {
return IOErrorFromErrno(errno, "Cannot delete directory entry '", path.ToString(),
"'");
}
return Status::OK();
}
Status DeleteDirTreeInternal(const PlatformFilename& dir_path) {
ARROW_ASSIGN_OR_RAISE(auto children, ListDir(dir_path));
for (const auto& child : children) {
struct stat lst;
PlatformFilename full_path = dir_path.Join(child);
RETURN_NOT_OK(LinkStat(full_path, &lst));
RETURN_NOT_OK(DeleteDirEntry(full_path, lst));
}
return Status::OK();
}
Result<bool> DeleteDirContents(const PlatformFilename& dir_path, bool allow_not_found,
bool remove_top_dir) {
bool exists = true;
struct stat lst;
if (allow_not_found) {
RETURN_NOT_OK(LinkStat(dir_path, &lst, &exists));
} else {
// Will raise if dir_path does not exist
RETURN_NOT_OK(LinkStat(dir_path, &lst));
}
if (exists) {
if (!S_ISDIR(lst.st_mode) && !S_ISLNK(lst.st_mode)) {
return Status::IOError("Cannot delete directory '", dir_path.ToString(),
"': not a directory");
}
RETURN_NOT_OK(DeleteDirEntryDir(dir_path, lst, remove_top_dir));
}
return exists;
}
#endif
} // namespace
Result<bool> DeleteDirContents(const PlatformFilename& dir_path, bool allow_not_found) {
return DeleteDirContents(dir_path, allow_not_found, /*remove_top_dir=*/false);
}
Result<bool> DeleteDirTree(const PlatformFilename& dir_path, bool allow_not_found) {
return DeleteDirContents(dir_path, allow_not_found, /*remove_top_dir=*/true);
}
Result<bool> DeleteFile(const PlatformFilename& file_path, bool allow_not_found) {
#ifdef _WIN32
if (DeleteFileW(file_path.ToNative().c_str())) {
return true;
} else {
int errnum = GetLastError();
if (!allow_not_found || errnum != ERROR_FILE_NOT_FOUND) {
return IOErrorFromWinError(GetLastError(), "Cannot delete file '",
file_path.ToString(), "'");
}
}
#else
if (unlink(file_path.ToNative().c_str()) == 0) {
return true;
} else {
if (!allow_not_found || errno != ENOENT) {
return IOErrorFromErrno(errno, "Cannot delete file '", file_path.ToString(), "'");
}
}
#endif
return false;
}
Result<bool> FileExists(const PlatformFilename& path) {
#ifdef _WIN32
if (GetFileAttributesW(path.ToNative().c_str()) != INVALID_FILE_ATTRIBUTES) {
return true;
} else {
int errnum = GetLastError();
if (errnum != ERROR_PATH_NOT_FOUND && errnum != ERROR_FILE_NOT_FOUND) {
return IOErrorFromWinError(GetLastError(), "Failed getting information for path '",
path.ToString(), "'");
}
return false;
}
#else
struct stat st;
if (stat(path.ToNative().c_str(), &st) == 0) {
return true;
} else {
if (errno != ENOENT && errno != ENOTDIR) {
return IOErrorFromErrno(errno, "Failed getting information for path '",
path.ToString(), "'");
}
return false;
}
#endif
}
//
// Creating and destroying file descriptors
//
FileDescriptor::FileDescriptor(FileDescriptor&& other) : fd_(other.fd_.exchange(-1)) {}
FileDescriptor& FileDescriptor::operator=(FileDescriptor&& other) {
int old_fd = fd_.exchange(other.fd_.exchange(-1));
if (old_fd != -1) {
CloseFromDestructor(old_fd);
}
return *this;
}
void FileDescriptor::CloseFromDestructor(int fd) {
ARROW_WARN_NOT_OK(FileClose(fd), "Failed to close file descriptor");
}
FileDescriptor::~FileDescriptor() {
int fd = fd_.load();
if (fd != -1) {
CloseFromDestructor(fd);
}
}
Status FileDescriptor::Close() {
int fd = fd_.exchange(-1);
if (fd != -1) {
return FileClose(fd);
}
return Status::OK();
}
int FileDescriptor::Detach() { return fd_.exchange(-1); }
static Result<int64_t> lseek64_compat(int fd, int64_t pos, int whence) {
#if defined(_WIN32)
int64_t ret = _lseeki64(fd, pos, whence);
#else
int64_t ret = lseek(fd, pos, whence);
#endif
if (ret == -1) {
return Status::IOError("lseek failed");
}
return ret;
}
Result<FileDescriptor> FileOpenReadable(const PlatformFilename& file_name) {
FileDescriptor fd;
#if defined(_WIN32)
HANDLE file_handle = CreateFileW(file_name.ToNative().c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
return IOErrorFromWinError(GetLastError(), "Failed to open local file '",
file_name.ToString(), "'");
}
int ret = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle),
_O_RDONLY | _O_BINARY | _O_NOINHERIT);
if (ret == -1) {
CloseHandle(file_handle);
return IOErrorFromErrno(errno, "Failed to open local file '", file_name.ToString(),
"'");
}
fd = FileDescriptor(ret);
#else
int ret = open(file_name.ToNative().c_str(), O_RDONLY);
if (ret < 0) {
return IOErrorFromErrno(errno, "Failed to open local file '", file_name.ToString(),
"'");
}
// open(O_RDONLY) succeeds on directories, check for it
fd = FileDescriptor(ret);
struct stat st;
ret = fstat(fd.fd(), &st);
if (ret == 0 && S_ISDIR(st.st_mode)) {
return Status::IOError("Cannot open for reading: path '", file_name.ToString(),
"' is a directory");
}
#endif
return fd;
}
Result<FileDescriptor> FileOpenWritable(const PlatformFilename& file_name,
bool write_only, bool truncate, bool append) {
FileDescriptor fd;
#if defined(_WIN32)
DWORD desired_access = GENERIC_WRITE;
DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
DWORD creation_disposition = OPEN_ALWAYS;
if (truncate) {
creation_disposition = CREATE_ALWAYS;
}
if (!write_only) {
desired_access |= GENERIC_READ;
}
HANDLE file_handle =
CreateFileW(file_name.ToNative().c_str(), desired_access, share_mode, NULL,
creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
return IOErrorFromWinError(GetLastError(), "Failed to open local file '",
file_name.ToString(), "'");
}
int ret = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle),
_O_RDONLY | _O_BINARY | _O_NOINHERIT);
if (ret == -1) {
CloseHandle(file_handle);
return IOErrorFromErrno(errno, "Failed to open local file '", file_name.ToString(),
"'");
}
fd = FileDescriptor(ret);
#else
int oflag = O_CREAT;
if (truncate) {
oflag |= O_TRUNC;
}
if (append) {
oflag |= O_APPEND;
}
if (write_only) {
oflag |= O_WRONLY;
} else {
oflag |= O_RDWR;
}
int ret = open(file_name.ToNative().c_str(), oflag, 0666);
if (ret == -1) {
return IOErrorFromErrno(errno, "Failed to open local file '", file_name.ToString(),
"'");
}
fd = FileDescriptor(ret);
#endif
if (append) {
// Seek to end, as O_APPEND does not necessarily do it
RETURN_NOT_OK(lseek64_compat(fd.fd(), 0, SEEK_END));
}
return fd;
}
Result<int64_t> FileTell(int fd) {
#if defined(_WIN32)
int64_t current_pos = _telli64(fd);
if (current_pos == -1) {
return Status::IOError("_telli64 failed");
}
return current_pos;
#else
return lseek64_compat(fd, 0, SEEK_CUR);
#endif
}
Result<Pipe> CreatePipe() {
bool ok;
int fds[2];
Pipe pipe;
#if defined(_WIN32)
ok = _pipe(fds, 4096, _O_BINARY) >= 0;
if (ok) {
pipe = {FileDescriptor(fds[0]), FileDescriptor(fds[1])};
}
#elif defined(__linux__) && defined(__GLIBC__)
// On Unix, we don't want the file descriptors to survive after an exec() call
ok = pipe2(fds, O_CLOEXEC) >= 0;
if (ok) {
pipe = {FileDescriptor(fds[0]), FileDescriptor(fds[1])};
}
#else
auto set_cloexec = [](int fd) -> bool {
int flags = fcntl(fd, F_GETFD);
if (flags >= 0) {
flags = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
return flags >= 0;
};
ok = ::pipe(fds) >= 0;
if (ok) {
pipe = {FileDescriptor(fds[0]), FileDescriptor(fds[1])};
ok &= set_cloexec(fds[0]);
if (ok) {
ok &= set_cloexec(fds[1]);
}
}
#endif
if (!ok) {
return IOErrorFromErrno(errno, "Error creating pipe");
}
return pipe;
}
Status SetPipeFileDescriptorNonBlocking(int fd) {
#if defined(_WIN32)
const auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
DWORD mode = PIPE_NOWAIT;
if (!SetNamedPipeHandleState(handle, &mode, nullptr, nullptr)) {
return IOErrorFromWinError(GetLastError(), "Error making pipe non-blocking");
}
#else
int flags = fcntl(fd, F_GETFL);
if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
return IOErrorFromErrno(errno, "Error making pipe non-blocking");
}
#endif
return Status::OK();
}
namespace {
#ifdef WIN32
# define PIPE_WRITE _write
# define PIPE_READ _read
#else
# define PIPE_WRITE write
# define PIPE_READ read
#endif
class SelfPipeImpl : public SelfPipe, public std::enable_shared_from_this<SelfPipeImpl> {
static constexpr uint64_t kEofPayload = 5804561806345822987ULL;
public:
explicit SelfPipeImpl(bool signal_safe) : signal_safe_(signal_safe) {}
Status Init() {
ARROW_ASSIGN_OR_RAISE(pipe_, CreatePipe());
if (signal_safe_) {
if (!please_shutdown_.is_lock_free()) {
return Status::IOError("Cannot use non-lock-free atomic in a signal handler");
}
// We cannot afford blocking writes in a signal handler
RETURN_NOT_OK(SetPipeFileDescriptorNonBlocking(pipe_.wfd.fd()));
}
atfork_handler_ = std::make_shared<AtForkHandler>(
/*before=*/
[weak_self = std::weak_ptr<SelfPipeImpl>(shared_from_this())] {
auto self = weak_self.lock();
if (self) {
self->BeforeFork();
}
return self;
},
/*parent_after=*/
[](std::any token) {
auto self = std::any_cast<std::shared_ptr<SelfPipeImpl>>(std::move(token));
self->ParentAfterFork();
},
/*child_after=*/
[](std::any token) {
auto self = std::any_cast<std::shared_ptr<SelfPipeImpl>>(std::move(token));
self->ChildAfterFork();
});
RegisterAtFork(atfork_handler_);
return Status::OK();
}
Result<uint64_t> Wait() override {
if (pipe_.rfd.closed()) {
// Already closed
return ClosedPipe();
}
uint64_t payload = 0;
char* buf = reinterpret_cast<char*>(&payload);
auto buf_size = static_cast<int64_t>(sizeof(payload));
while (buf_size > 0) {
int64_t n_read = PIPE_READ(pipe_.rfd.fd(), buf, static_cast<uint32_t>(buf_size));
if (n_read < 0) {
if (errno == EINTR) {
continue;
}
if (pipe_.rfd.closed()) {
return ClosedPipe();
}
return IOErrorFromErrno(errno, "Failed reading from self-pipe");
}
buf += n_read;
buf_size -= n_read;
}
if (payload == kEofPayload && please_shutdown_.load()) {
RETURN_NOT_OK(pipe_.rfd.Close());
return ClosedPipe();
}
return payload;
}
// XXX return StatusCode from here?
void Send(uint64_t payload) override {
if (signal_safe_) {
int saved_errno = errno;
DoSend(payload);
errno = saved_errno;
} else {
DoSend(payload);
}
}
Status Shutdown() override {
please_shutdown_.store(true);
errno = 0;
if (!DoSend(kEofPayload)) {
if (errno) {
return IOErrorFromErrno(errno, "Could not shutdown self-pipe");
} else if (!pipe_.wfd.closed()) {
return Status::UnknownError("Could not shutdown self-pipe");
}
}
return pipe_.wfd.Close();
}
~SelfPipeImpl() { ARROW_WARN_NOT_OK(Shutdown(), "On self-pipe destruction"); }
protected:
void BeforeFork() {}
void ParentAfterFork() {}
void ChildAfterFork() {
// Close and recreate pipe, to avoid interfering with parent.
const bool was_closed = pipe_.rfd.closed() || pipe_.wfd.closed();
ARROW_CHECK_OK(pipe_.Close());
if (!was_closed) {
ARROW_CHECK_OK(CreatePipe().Value(&pipe_));
}
}
Status ClosedPipe() const { return Status::Invalid("Self-pipe closed"); }
bool DoSend(uint64_t payload) {
// This needs to be async-signal safe as it's called from Send()
if (pipe_.wfd.closed()) {
// Already closed
return false;
}
const char* buf = reinterpret_cast<const char*>(&payload);
auto buf_size = static_cast<int64_t>(sizeof(payload));
while (buf_size > 0) {
int64_t n_written =
PIPE_WRITE(pipe_.wfd.fd(), buf, static_cast<uint32_t>(buf_size));
if (n_written < 0) {
if (errno == EINTR) {
continue;
} else {
// Perhaps EAGAIN if non-blocking, or EBADF if closed in the meantime?
// In any case, we can't do anything more here.
break;
}
}
buf += n_written;
buf_size -= n_written;
}
return buf_size == 0;
}
const bool signal_safe_;
Pipe pipe_;
std::atomic<bool> please_shutdown_{false};
std::shared_ptr<AtForkHandler> atfork_handler_;
};
#undef PIPE_WRITE
#undef PIPE_READ
} // namespace
Result<std::shared_ptr<SelfPipe>> SelfPipe::Make(bool signal_safe) {
auto ptr = std::make_shared<SelfPipeImpl>(signal_safe);
RETURN_NOT_OK(ptr->Init());
return ptr;
}
SelfPipe::~SelfPipe() = default;
namespace {
Status StatusFromMmapErrno(const char* prefix) {
#ifdef _WIN32
errno = __map_mman_error(GetLastError(), EPERM);
#endif
return IOErrorFromErrno(errno, prefix);
}
int64_t GetPageSizeInternal() {
#if defined(__APPLE__)
return getpagesize();
#elif defined(_WIN32)
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwPageSize;
#else
errno = 0;
const auto ret = sysconf(_SC_PAGESIZE);
if (ret == -1) {
ARROW_LOG(FATAL) << "sysconf(_SC_PAGESIZE) failed: " << ErrnoMessage(errno);
}
return static_cast<int64_t>(ret);
#endif
}
} // namespace
int64_t GetPageSize() {
static const int64_t kPageSize = GetPageSizeInternal(); // cache it
return kPageSize;
}
//
// Compatible way to remap a memory map
//
Status MemoryMapRemap(void* addr, size_t old_size, size_t new_size, int fildes,
void** new_addr) {
// should only be called with writable files
*new_addr = MAP_FAILED;
#ifdef _WIN32
// flags are ignored on windows
HANDLE fm, h;
if (!UnmapViewOfFile(addr)) {
return StatusFromMmapErrno("UnmapViewOfFile failed");
}
h = reinterpret_cast<HANDLE>(_get_osfhandle(fildes));
if (h == INVALID_HANDLE_VALUE) {
return StatusFromMmapErrno("Cannot get file handle");
}
uint64_t new_size64 = new_size;
LONG new_size_low = static_cast<LONG>(new_size64 & 0xFFFFFFFFUL);
LONG new_size_high = static_cast<LONG>((new_size64 >> 32) & 0xFFFFFFFFUL);
SetFilePointer(h, new_size_low, &new_size_high, FILE_BEGIN);
SetEndOfFile(h);
fm = CreateFileMapping(h, NULL, PAGE_READWRITE, 0, 0, "");
if (fm == NULL) {
return StatusFromMmapErrno("CreateFileMapping failed");
}
*new_addr = MapViewOfFile(fm, FILE_MAP_WRITE, 0, 0, new_size);
CloseHandle(fm);
if (new_addr == NULL) {
return StatusFromMmapErrno("MapViewOfFile failed");
}
return Status::OK();
#elif defined(__linux__)
if (ftruncate(fildes, new_size) == -1) {
return StatusFromMmapErrno("ftruncate failed");
}
*new_addr = mremap(addr, old_size, new_size, MREMAP_MAYMOVE);
if (*new_addr == MAP_FAILED) {
return StatusFromMmapErrno("mremap failed");
}
return Status::OK();
#else
// we have to close the mmap first, truncate the file to the new size
// and recreate the mmap
if (munmap(addr, old_size) == -1) {
return StatusFromMmapErrno("munmap failed");
}
if (ftruncate(fildes, new_size) == -1) {
return StatusFromMmapErrno("ftruncate failed");
}
// we set READ / WRITE flags on the new map, since we could only have
// enlarged a RW map in the first place
*new_addr = mmap(NULL, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, fildes, 0);
if (*new_addr == MAP_FAILED) {
return StatusFromMmapErrno("mmap failed");
}
return Status::OK();
#endif
}
Status MemoryAdviseWillNeed(const std::vector<MemoryRegion>& regions) {
#ifndef __EMSCRIPTEN__
const auto page_size = static_cast<size_t>(GetPageSize());
DCHECK_GT(page_size, 0);
const size_t page_mask = ~(page_size - 1);
DCHECK_EQ(page_mask & page_size, page_size);
auto align_region = [=](const MemoryRegion& region) -> MemoryRegion {
const auto addr = reinterpret_cast<uintptr_t>(region.addr);
const auto aligned_addr = addr & page_mask;
DCHECK_LT(addr - aligned_addr, page_size);
return {reinterpret_cast<void*>(aligned_addr),
region.size + static_cast<size_t>(addr - aligned_addr)};
};
# ifdef _WIN32
// PrefetchVirtualMemory() is available on Windows 8 or later
struct PrefetchEntry { // Like WIN32_MEMORY_RANGE_ENTRY
void* VirtualAddress;
size_t NumberOfBytes;
PrefetchEntry(const MemoryRegion& region) // NOLINT runtime/explicit
: VirtualAddress(region.addr), NumberOfBytes(region.size) {}
};
using PrefetchVirtualMemoryFunc = BOOL (*)(HANDLE, ULONG_PTR, PrefetchEntry*, ULONG);
static const auto prefetch_virtual_memory = reinterpret_cast<PrefetchVirtualMemoryFunc>(
GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"));
if (prefetch_virtual_memory != nullptr) {
std::vector<PrefetchEntry> entries;
entries.reserve(regions.size());
for (const auto& region : regions) {
if (region.size != 0) {
entries.emplace_back(align_region(region));
}
}
if (!entries.empty() &&
!prefetch_virtual_memory(GetCurrentProcess(),
static_cast<ULONG_PTR>(entries.size()), entries.data(),
0)) {
return IOErrorFromWinError(GetLastError(), "PrefetchVirtualMemory failed");
}
}
return Status::OK();
# elif defined(POSIX_MADV_WILLNEED)
for (const auto& region : regions) {
if (region.size != 0) {
const auto aligned = align_region(region);
int err = posix_madvise(aligned.addr, aligned.size, POSIX_MADV_WILLNEED);
// EBADF can be returned on Linux in the following cases:
// - the kernel version is older than 3.9
// - the kernel was compiled with CONFIG_SWAP disabled (ARROW-9577)
if (err != 0 && err != EBADF) {
return IOErrorFromErrno(err, "posix_madvise failed");
}
}
}
return Status::OK();
# else
return Status::OK();
# endif
#else
return Status::OK();
#endif
}
//
// Closing files
//
Status FileClose(int fd) {
int ret;
#if defined(_WIN32)
ret = static_cast<int>(_close(fd));
#else
ret = static_cast<int>(close(fd));
#endif
if (ret == -1) {
return Status::IOError("error closing file");
}
return Status::OK();
}
//
// Seeking and telling
//
Status FileSeek(int fd, int64_t pos, int whence) {
return lseek64_compat(fd, pos, whence).status();
}
Status FileSeek(int fd, int64_t pos) { return FileSeek(fd, pos, SEEK_SET); }
Result<int64_t> FileGetSize(int fd) {
#if defined(_WIN32)
struct __stat64 st;
#else
struct stat st;
#endif
st.st_size = -1;
#if defined(_WIN32)
int ret = _fstat64(fd, &st);
#else
int ret = fstat(fd, &st);
#endif
if (ret == -1) {
return Status::IOError("error stat()ing file");
}
if (st.st_size == 0) {
// Maybe the file doesn't support getting its size, double-check by
// trying to tell() (seekable files usually have a size, while
// non-seekable files don't)
RETURN_NOT_OK(FileTell(fd));
} else if (st.st_size < 0) {
return Status::IOError("error getting file size");
}
return st.st_size;
}
//
// Reading data
//
static inline int64_t pread_compat(int fd, void* buf, int64_t nbytes, int64_t pos) {
#if defined(_WIN32)
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
DWORD dwBytesRead = 0;
OVERLAPPED overlapped = {};
overlapped.Offset = static_cast<uint32_t>(pos);
overlapped.OffsetHigh = static_cast<uint32_t>(pos >> 32);
// Note: ReadFile() will update the file position
BOOL bRet =
ReadFile(handle, buf, static_cast<uint32_t>(nbytes), &dwBytesRead, &overlapped);
if (bRet || GetLastError() == ERROR_HANDLE_EOF) {
return dwBytesRead;
} else {
return -1;
}
#else
int64_t ret;
do {
ret = static_cast<int64_t>(
pread(fd, buf, static_cast<size_t>(nbytes), static_cast<off_t>(pos)));
} while (ret == -1 && errno == EINTR);
return ret;
#endif
}
Result<int64_t> FileRead(int fd, uint8_t* buffer, int64_t nbytes) {
#if defined(_WIN32)
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
#endif
int64_t total_bytes_read = 0;
while (total_bytes_read < nbytes) {
const int64_t chunksize =
std::min(static_cast<int64_t>(ARROW_MAX_IO_CHUNKSIZE), nbytes - total_bytes_read);
int64_t bytes_read = 0;
#if defined(_WIN32)
DWORD dwBytesRead = 0;
if (!ReadFile(handle, buffer, static_cast<uint32_t>(chunksize), &dwBytesRead,
nullptr)) {
auto errnum = GetLastError();
// Return a normal EOF when the write end of a pipe was closed
if (errnum != ERROR_HANDLE_EOF && errnum != ERROR_BROKEN_PIPE) {
return IOErrorFromWinError(GetLastError(), "Error reading bytes from file");
}
}
bytes_read = dwBytesRead;
#else
bytes_read = static_cast<int64_t>(read(fd, buffer, static_cast<size_t>(chunksize)));
if (bytes_read == -1) {
if (errno == EINTR) {
continue;
}
return IOErrorFromErrno(errno, "Error reading bytes from file");
}
#endif
if (bytes_read == 0) {
// EOF
break;
}
buffer += bytes_read;
total_bytes_read += bytes_read;
}
return total_bytes_read;
}
Result<int64_t> FileReadAt(int fd, uint8_t* buffer, int64_t position, int64_t nbytes) {
int64_t bytes_read = 0;
while (bytes_read < nbytes) {
int64_t chunksize =
std::min(static_cast<int64_t>(ARROW_MAX_IO_CHUNKSIZE), nbytes - bytes_read);
int64_t ret = pread_compat(fd, buffer, chunksize, position);
if (ret == -1) {
return IOErrorFromErrno(errno, "Error reading bytes from file");
}
if (ret == 0) {
// EOF
break;
}
buffer += ret;
position += ret;
bytes_read += ret;
}
return bytes_read;
}
//
// Writing data
//
Status FileWrite(int fd, const uint8_t* buffer, const int64_t nbytes) {
int64_t bytes_written = 0;
while (bytes_written < nbytes) {
const int64_t chunksize =
std::min(static_cast<int64_t>(ARROW_MAX_IO_CHUNKSIZE), nbytes - bytes_written);
#if defined(_WIN32)
int64_t ret = static_cast<int64_t>(
_write(fd, buffer + bytes_written, static_cast<uint32_t>(chunksize)));
#else
int64_t ret = static_cast<int64_t>(
write(fd, buffer + bytes_written, static_cast<size_t>(chunksize)));
if (ret == -1 && errno == EINTR) {
continue;
}
#endif
if (ret == -1) {
return IOErrorFromErrno(errno, "Error writing bytes to file");
}
bytes_written += ret;
}
return Status::OK();
}
Status FileTruncate(int fd, const int64_t size) {
int ret, errno_actual;
#ifdef _WIN32
errno_actual = _chsize_s(fd, static_cast<size_t>(size));
ret = errno_actual == 0 ? 0 : -1;
#else
ret = ftruncate(fd, static_cast<size_t>(size));
errno_actual = errno;
#endif
if (ret == -1) {
return IOErrorFromErrno(errno_actual, "Error writing bytes to file");
}
return Status::OK();
}
//
// Environment variables
//
Result<std::string> GetEnvVar(const char* name) {
#ifdef _WIN32
// On Windows, getenv() reads an early copy of the process' environment
// which doesn't get updated when SetEnvironmentVariable() is called.
constexpr int32_t bufsize = 2000;
char c_str[bufsize];
auto res = GetEnvironmentVariableA(name, c_str, bufsize);
if (res >= bufsize) {
return Status::CapacityError("environment variable value too long");
} else if (res == 0) {
return Status::KeyError("environment variable undefined");
}
return std::string(c_str);
#else
char* c_str = getenv(name);
if (c_str == nullptr) {
return Status::KeyError("environment variable undefined");
}
return std::string(c_str);
#endif
}
Result<std::string> GetEnvVar(const std::string& name) { return GetEnvVar(name.c_str()); }
#ifdef _WIN32
Result<NativePathString> GetEnvVarNative(const std::string& name) {
NativePathString w_name;
constexpr int32_t bufsize = 2000;
wchar_t w_str[bufsize];
ARROW_ASSIGN_OR_RAISE(w_name, StringToNative(name));
auto res = GetEnvironmentVariableW(w_name.c_str(), w_str, bufsize);
if (res >= bufsize) {
return Status::CapacityError("environment variable value too long");
} else if (res == 0) {
return Status::KeyError("environment variable undefined");
}
return NativePathString(w_str);
}
Result<NativePathString> GetEnvVarNative(const char* name) {
return GetEnvVarNative(std::string(name));
}
#else
Result<NativePathString> GetEnvVarNative(const std::string& name) {
return GetEnvVar(name);
}
Result<NativePathString> GetEnvVarNative(const char* name) { return GetEnvVar(name); }
#endif
Status SetEnvVar(const char* name, const char* value) {
#ifdef _WIN32
if (SetEnvironmentVariableA(name, value)) {
return Status::OK();
} else {
return Status::Invalid("failed setting environment variable");
}
#else
if (setenv(name, value, 1) == 0) {
return Status::OK();
} else {
return Status::Invalid("failed setting environment variable");
}
#endif
}
Status SetEnvVar(const std::string& name, const std::string& value) {
return SetEnvVar(name.c_str(), value.c_str());
}
Status DelEnvVar(const char* name) {
#ifdef _WIN32
if (SetEnvironmentVariableA(name, nullptr)) {
return Status::OK();
} else {
return Status::Invalid("failed deleting environment variable");
}
#else
if (unsetenv(name) == 0) {
return Status::OK();
} else {
return Status::Invalid("failed deleting environment variable");
}
#endif
}
Status DelEnvVar(const std::string& name) { return DelEnvVar(name.c_str()); }
//
// Temporary directories
//
namespace {
#if _WIN32
NativePathString GetWindowsDirectoryPath() {
auto size = GetWindowsDirectoryW(nullptr, 0);
ARROW_CHECK_GT(size, 0) << "GetWindowsDirectoryW failed";
std::vector<wchar_t> w_str(size);
size = GetWindowsDirectoryW(w_str.data(), size);
ARROW_CHECK_GT(size, 0) << "GetWindowsDirectoryW failed";
return {w_str.data(), size};
}
#endif
// Return a list of preferred locations for temporary files
std::vector<NativePathString> GetPlatformTemporaryDirs() {
struct TempDirSelector {
std::string env_var;
NativePathString path_append;
};
std::vector<TempDirSelector> selectors;
NativePathString fallback_tmp;
#if _WIN32
selectors = {
{"TMP", L""}, {"TEMP", L""}, {"LOCALAPPDATA", L"Temp"}, {"USERPROFILE", L"Temp"}};
fallback_tmp = GetWindowsDirectoryPath();
#else
selectors = {{"TMPDIR", ""}, {"TMP", ""}, {"TEMP", ""}, {"TEMPDIR", ""}};
# ifdef __ANDROID__
fallback_tmp = "/data/local/tmp";
# else
fallback_tmp = "/tmp";
# endif
#endif
std::vector<NativePathString> temp_dirs;
for (const auto& sel : selectors) {
auto result = GetEnvVarNative(sel.env_var);
if (result.status().IsKeyError()) {
// Environment variable absent, skip
continue;
}
if (!result.ok()) {
ARROW_LOG(WARNING) << "Failed getting env var '" << sel.env_var
<< "': " << result.status().ToString();
continue;
}
NativePathString p = *std::move(result);
if (p.empty()) {
// Environment variable set to empty string, skip
continue;
}
if (sel.path_append.empty()) {
temp_dirs.push_back(p);
} else {
temp_dirs.push_back(p + kNativeSep + sel.path_append);
}
}
temp_dirs.push_back(fallback_tmp);
return temp_dirs;
}
std::string MakeRandomName(int num_chars) {
constexpr std::string_view chars = "0123456789abcdefghijklmnopqrstuvwxyz";
std::default_random_engine gen(
static_cast<std::default_random_engine::result_type>(GetRandomSeed()));
std::uniform_int_distribution<int> dist(0, static_cast<int>(chars.length() - 1));
std::string s;
s.reserve(num_chars);
for (int i = 0; i < num_chars; ++i) {
s += chars[dist(gen)];
}
return s;
}
} // namespace
Result<std::unique_ptr<TemporaryDir>> TemporaryDir::Make(const std::string& prefix) {
const int kNumChars = 8;
NativePathString base_name;
auto MakeBaseName = [&]() {
std::string suffix = MakeRandomName(kNumChars);
return StringToNative(prefix + suffix);
};
auto TryCreatingDirectory =
[&](const NativePathString& base_dir) -> Result<std::unique_ptr<TemporaryDir>> {
Status st;
for (int attempt = 0; attempt < 3; ++attempt) {
PlatformFilename fn_base_dir(base_dir);
PlatformFilename fn_base_name(base_name + kNativeSep);
PlatformFilename fn = fn_base_dir.Join(fn_base_name);
auto result = CreateDir(fn);
if (!result.ok()) {
// Probably a permissions error or a non-existing base_dir
return nullptr;
}
if (*result) {
return std::unique_ptr<TemporaryDir>(new TemporaryDir(std::move(fn)));
}
// The random name already exists in base_dir, try with another name
st = Status::IOError("Path already exists: '", fn.ToString(), "'");
ARROW_ASSIGN_OR_RAISE(base_name, MakeBaseName());
}
return st;
};
ARROW_ASSIGN_OR_RAISE(base_name, MakeBaseName());
auto base_dirs = GetPlatformTemporaryDirs();
DCHECK_NE(base_dirs.size(), 0);
for (const auto& base_dir : base_dirs) {
ARROW_ASSIGN_OR_RAISE(auto ptr, TryCreatingDirectory(base_dir));
if (ptr) {
return ptr;
}
// Cannot create in this directory, try the next one
}
return Status::IOError(
"Cannot create temporary subdirectory in any "
"of the platform temporary directories");
}
TemporaryDir::TemporaryDir(PlatformFilename&& path) : path_(std::move(path)) {}
TemporaryDir::~TemporaryDir() {
ARROW_WARN_NOT_OK(DeleteDirTree(path_).status(),
"When trying to delete temporary directory");
}
SignalHandler::SignalHandler() : SignalHandler(static_cast<Callback>(nullptr)) {}
SignalHandler::SignalHandler(Callback cb) {
#if ARROW_HAVE_SIGACTION
sa_.sa_handler = cb;
sa_.sa_flags = 0;
sigemptyset(&sa_.sa_mask);
#else
cb_ = cb;
#endif
}
#if ARROW_HAVE_SIGACTION
SignalHandler::SignalHandler(const struct sigaction& sa) {
memcpy(&sa_, &sa, sizeof(sa));
}
#endif
SignalHandler::Callback SignalHandler::callback() const {
#if ARROW_HAVE_SIGACTION
return sa_.sa_handler;
#else
return cb_;
#endif
}
#if ARROW_HAVE_SIGACTION
const struct sigaction& SignalHandler::action() const { return sa_; }
#endif
Result<SignalHandler> GetSignalHandler(int signum) {
#if ARROW_HAVE_SIGACTION
struct sigaction sa;
int ret = sigaction(signum, nullptr, &sa);
if (ret != 0) {
// TODO more detailed message using errno
return Status::IOError("sigaction call failed");
}
return SignalHandler(sa);
#else
// To read the old handler, set the signal handler to something else temporarily
SignalHandler::Callback cb = signal(signum, SIG_IGN);
if (cb == SIG_ERR || signal(signum, cb) == SIG_ERR) {
// TODO more detailed message using errno
return Status::IOError("signal call failed");
}
return SignalHandler(cb);
#endif
}
Result<SignalHandler> SetSignalHandler(int signum, const SignalHandler& handler) {
#if ARROW_HAVE_SIGACTION
struct sigaction old_sa;
int ret = sigaction(signum, &handler.action(), &old_sa);
if (ret != 0) {
// TODO more detailed message using errno
return Status::IOError("sigaction call failed");
}
return SignalHandler(old_sa);
#else
SignalHandler::Callback cb = signal(signum, handler.callback());
if (cb == SIG_ERR) {
// TODO more detailed message using errno
return Status::IOError("signal call failed");
}
return SignalHandler(cb);
#endif
return Status::OK();
}
void ReinstateSignalHandler(int signum, SignalHandler::Callback handler) {
#if !ARROW_HAVE_SIGACTION
// Cannot report any errors from signal() (but there shouldn't be any)
signal(signum, handler);
#endif
}
Status SendSignal(int signum) {
if (raise(signum) == 0) {
return Status::OK();
}
if (errno == EINVAL) {
return Status::Invalid("Invalid signal number ", signum);
}
return IOErrorFromErrno(errno, "Failed to raise signal");
}
Status SendSignalToThread(int signum, uint64_t thread_id) {
#ifndef ARROW_ENABLE_THREADING
return Status::NotImplemented("Can't send signal with no threads");
#elif defined(_WIN32)
return Status::NotImplemented("Cannot send signal to specific thread on Windows");
#else
// Have to use a C-style cast because pthread_t can be a pointer *or* integer type
int r = pthread_kill((pthread_t)thread_id, signum); // NOLINT readability-casting
if (r == 0) {
return Status::OK();
}
if (r == EINVAL) {
return Status::Invalid("Invalid signal number ", signum);
}
return IOErrorFromErrno(r, "Failed to raise signal");
#endif
}
namespace {
int64_t GetPid() {
#ifdef _WIN32
return GetCurrentProcessId();
#else
return getpid();
#endif
}
std::mt19937_64 GetSeedGenerator() {
// Initialize Mersenne Twister PRNG with a true random seed.
// Make sure to mix in process id to minimize risks of clashes when parallel testing.
#ifdef ARROW_VALGRIND
// Valgrind can crash, hang or enter an infinite loop on std::random_device,
// use a crude initializer instead.
const uint8_t dummy = 0;
ARROW_UNUSED(dummy);
std::mt19937_64 seed_gen(reinterpret_cast<uintptr_t>(&dummy) ^
static_cast<uintptr_t>(GetPid()));
#else
std::random_device true_random;
std::mt19937_64 seed_gen(static_cast<uint64_t>(true_random()) ^
(static_cast<uint64_t>(true_random()) << 32) ^
static_cast<uint64_t>(GetPid()));
#endif
return seed_gen;
}
} // namespace
int64_t GetRandomSeed() {
// The process-global seed generator to aims to avoid calling std::random_device
// unless truly necessary (it can block on some systems, see ARROW-10287).
static auto seed_gen = GetSeedGenerator();
static std::mutex seed_gen_mutex;
std::lock_guard<std::mutex> lock(seed_gen_mutex);
return static_cast<int64_t>(seed_gen());
}
uint64_t GetThreadId() {
uint64_t equiv{0};
// std::thread::id is trivially copyable as per C++ spec,
// so type punning as a uint64_t should work
static_assert(sizeof(std::thread::id) <= sizeof(uint64_t),
"std::thread::id can't fit into uint64_t");
const auto tid = std::this_thread::get_id();
memcpy(&equiv, reinterpret_cast<const void*>(&tid), sizeof(tid));
return equiv;
}
uint64_t GetOptionalThreadId() {
auto tid = GetThreadId();
return (tid == 0) ? tid - 1 : tid;
}
// Returns the current resident set size (physical memory use) measured
// in bytes, or zero if the value cannot be determined on this OS.
int64_t GetCurrentRSS() {
#if defined(_WIN32)
// Windows --------------------------------------------------
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return static_cast<int64_t>(info.WorkingSetSize);
#elif defined(__APPLE__)
// OSX ------------------------------------------------------
# ifdef MACH_TASK_BASIC_INFO
struct mach_task_basic_info info;
mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) !=
KERN_SUCCESS) {
ARROW_LOG(WARNING) << "Can't resolve RSS value";
return 0;
}
# else
struct task_basic_info info;
mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &infoCount) !=
KERN_SUCCESS) {
ARROW_LOG(WARNING) << "Can't resolve RSS value";
return 0;
}
# endif
return static_cast<int64_t>(info.resident_size);
#elif defined(__linux__)
// Linux ----------------------------------------------------
int64_t rss = 0L;
std::ifstream fp("/proc/self/statm");
if (fp) {
fp >> rss;
return rss * sysconf(_SC_PAGESIZE);
} else {
ARROW_LOG(WARNING) << "Can't resolve RSS value from /proc/self/statm";
return 0;
}
#else
// AIX, BSD, Solaris, and Unknown OS ------------------------
return 0; // Unsupported.
#endif
}
int64_t GetTotalMemoryBytes() {
#if defined(_WIN32)
ULONGLONG result_kb;
if (!GetPhysicallyInstalledSystemMemory(&result_kb)) {
ARROW_LOG(WARNING) << "Failed to resolve total RAM size: "
<< std::strerror(GetLastError());
return -1;
}
return static_cast<int64_t>(result_kb * 1024);
#elif defined(__APPLE__)
int64_t result;
size_t size = sizeof(result);
if (sysctlbyname("hw.memsize", &result, &size, nullptr, 0) == -1) {
ARROW_LOG(WARNING) << "Failed to resolve total RAM size";
return -1;
}
return result;
#elif defined(__linux__)
struct sysinfo info;
if (sysinfo(&info) == -1) {
ARROW_LOG(WARNING) << "Failed to resolve total RAM size: " << std::strerror(errno);
return -1;
}
return static_cast<int64_t>(info.totalram * info.mem_unit);
#else
return 0;
#endif
}
Result<void*> LoadDynamicLibrary(const char* path) {
#ifdef _WIN32
ARROW_ASSIGN_OR_RAISE(auto platform_path, PlatformFilename::FromString(path));
return LoadDynamicLibrary(platform_path);
#else
constexpr int kFlags =
// All undefined symbols in the shared object are resolved before dlopen() returns.
RTLD_NOW
// Symbols defined in this shared object are not made available to
// resolve references in subsequently loaded shared objects.
| RTLD_LOCAL;
if (void* handle = dlopen(path, kFlags)) return handle;
// dlopen(3) man page: "If dlopen() fails for any reason, it returns NULL."
// There is no null-returning non-error condition.
auto* error = dlerror();
return Status::IOError("dlopen(", path, ") failed: ", error ? error : "unknown error");
#endif
}
Result<void*> LoadDynamicLibrary(const PlatformFilename& path) {
#ifdef _WIN32
if (void* handle = LoadLibraryW(path.ToNative().c_str())) {
return handle;
}
// win32 api doc: "If the function fails, the return value is NULL."
// There is no null-returning non-error condition.
return IOErrorFromWinError(GetLastError(), "LoadLibrary(", path.ToString(), ") failed");
#else
return LoadDynamicLibrary(path.ToNative().c_str());
#endif
}
Result<void*> GetSymbol(void* handle, const char* name) {
if (handle == nullptr) {
return Status::Invalid("Attempting to retrieve symbol '", name,
"' from null library handle");
}
#ifdef _WIN32
if (void* sym = reinterpret_cast<void*>(
GetProcAddress(reinterpret_cast<HMODULE>(handle), name))) {
return sym;
}
// win32 api doc: "If the function fails, the return value is NULL."
// There is no null-returning non-error condition.
return IOErrorFromWinError(GetLastError(), "GetProcAddress(", name, ") failed.");
#else
if (void* sym = dlsym(handle, name)) return sym;
// dlsym(3) man page: "On failure, they return NULL"
// There is no null-returning non-error condition.
auto* error = dlerror();
return Status::IOError("dlsym(", name, ") failed: ", error ? error : "unknown error");
#endif
}
} // namespace arrow20::internal
|