-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
io_util.cc
1521 lines (1295 loc) · 41.3 KB
/
io_util.cc
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
// 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
#include "arrow/util/windows_compatibility.h" // IWYU pragma: keep
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h> // IWYU pragma: keep
// Defines that don't exist in MinGW
#if defined(__MINGW32__)
#define ARROW_WRITE_SHMODE S_IRUSR | S_IWUSR
#elif defined(_MSC_VER) // Visual Studio
#else // gcc / clang on POSIX platforms
#define ARROW_WRITE_SHMODE S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
#endif
// ----------------------------------------------------------------------
// file compatibility stuff
#ifdef _WIN32
#include <io.h>
#include <share.h>
#else // POSIX-like platforms
#include <dirent.h>
#endif
#ifdef _WIN32
#include "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 "arrow/buffer.h"
#include "arrow/result.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/io_util.h"
#include "arrow/util/logging.h"
// For filename conversion
#if defined(_WIN32)
#include "arrow/util/utf8.h"
#endif
namespace arrow {
using internal::checked_cast;
namespace io {
//
// StdoutStream implementation
//
StdoutStream::StdoutStream() : pos_(0) { set_mode(FileMode::WRITE); }
Status StdoutStream::Close() { return Status::OK(); }
bool StdoutStream::closed() const { return false; }
Result<int64_t> StdoutStream::Tell() const { return pos_; }
Status StdoutStream::Write(const void* data, int64_t nbytes) {
pos_ += nbytes;
std::cout.write(reinterpret_cast<const char*>(data), nbytes);
return Status::OK();
}
//
// StderrStream implementation
//
StderrStream::StderrStream() : pos_(0) { set_mode(FileMode::WRITE); }
Status StderrStream::Close() { return Status::OK(); }
bool StderrStream::closed() const { return false; }
Result<int64_t> StderrStream::Tell() const { return pos_; }
Status StderrStream::Write(const void* data, int64_t nbytes) {
pos_ += nbytes;
std::cerr.write(reinterpret_cast<const char*>(data), nbytes);
return Status::OK();
}
//
// StdinStream implementation
//
StdinStream::StdinStream() : pos_(0) { set_mode(FileMode::READ); }
Status StdinStream::Close() { return Status::OK(); }
bool StdinStream::closed() const { return false; }
Result<int64_t> StdinStream::Tell() const { return pos_; }
Result<int64_t> StdinStream::Read(int64_t nbytes, void* out) {
std::cin.read(reinterpret_cast<char*>(out), nbytes);
if (std::cin) {
pos_ += nbytes;
return nbytes;
} else {
return 0;
}
}
Result<std::shared_ptr<Buffer>> StdinStream::Read(int64_t nbytes) {
ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateResizableBuffer(nbytes));
ARROW_ASSIGN_OR_RAISE(int64_t bytes_read, Read(nbytes, buffer->mutable_data()));
ARROW_RETURN_NOT_OK(buffer->Resize(bytes_read, false));
buffer->ZeroPadding();
return std::move(buffer);
}
} // namespace io
namespace 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(const std::string& s) {
#if _WIN32
return ::arrow::util::UTF8ToWideString(s);
#else
return s;
#endif
}
#if _WIN32
Result<std::string> NativeToString(const NativePathString& ws) {
return ::arrow::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(const std::string& 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) {
char buf[1024];
auto nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errnum, 0, buf, sizeof(buf), NULL);
if (nchars == 0) {
// Fallback
std::stringstream ss;
ss << "Windows error #" << errnum;
return ss.str();
}
return std::string(buf, nchars);
}
#endif
namespace {
const char kErrnoDetailTypeId[] = "arrow::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[] = "arrow::WinErrorDetail";
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_; }
protected:
int errnum_;
};
#endif
} // namespace
std::shared_ptr<StatusDetail> StatusDetailFromErrno(int errnum) {
return std::make_shared<ErrnoDetail>(errnum);
}
#if _WIN32
std::shared_ptr<StatusDetail> StatusDetailFromWinError(int errnum) {
return std::make_shared<WinErrorDetail>(errnum);
}
#endif
int ErrnoFromStatus(const Status& status) {
const auto detail = status.detail();
if (detail != nullptr && detail->type_id() == kErrnoDetailTypeId) {
return checked_cast<const ErrnoDetail&>(*detail).errnum();
}
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;
}
//
// 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(const NativePathString& path)
: PlatformFilename(Impl{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::FromString(const std::string& 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(const std::string& child_name) const {
ARROW_ASSIGN_OR_RAISE(auto child, PlatformFilename::FromString(child_name));
return Join(child);
}
//
// Filesystem access routines
//
namespace {
Result<bool> DoCreateDir(const PlatformFilename& dir_path, bool create_parents) {
#ifdef _WIN32
if (CreateDirectoryW(dir_path.ToNative().c_str(), nullptr)) {
return true;
}
int errnum = GetLastError();
if (errnum == ERROR_ALREADY_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
if (mkdir(dir_path.ToNative().c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0) {
return true;
}
if (errno == EEXIST) {
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
}
//
// Functions for creating file descriptors
//
#define CHECK_LSEEK(retval) \
if ((retval) == -1) return Status::IOError("lseek failed");
static inline int64_t lseek64_compat(int fd, int64_t pos, int whence) {
#if defined(_WIN32)
return _lseeki64(fd, pos, whence);
#else
return lseek(fd, pos, whence);
#endif
}
static inline Result<int> CheckFileOpResult(int fd_ret, int errno_actual,
const PlatformFilename& file_name,
const char* opname) {
if (fd_ret == -1) {
#ifdef _WIN32
int winerr = GetLastError();
if (winerr != ERROR_SUCCESS) {
return IOErrorFromWinError(GetLastError(), "Failed to ", opname, " file '",
file_name.ToString(), "'");
}
#endif
return IOErrorFromErrno(errno_actual, "Failed to ", opname, " file '",
file_name.ToString(), "'");
}
return fd_ret;
}
Result<int> FileOpenReadable(const PlatformFilename& file_name) {
int fd, errno_actual;
#if defined(_WIN32)
SetLastError(0);
HANDLE file_handle = CreateFileW(file_name.ToNative().c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD last_error = GetLastError();
if (last_error == ERROR_SUCCESS) {
errno_actual = 0;
fd = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle),
_O_RDONLY | _O_BINARY | _O_NOINHERIT);
} else {
return IOErrorFromWinError(last_error, "Failed to open local file '",
file_name.ToString(), "'");
}
#else
fd = open(file_name.ToNative().c_str(), O_RDONLY);
errno_actual = errno;
if (fd >= 0) {
// open(O_RDONLY) succeeds on directories, check for it
struct stat st;
int ret = fstat(fd, &st);
if (ret == -1) {
ARROW_UNUSED(FileClose(fd));
// Will propagate error below
} else if (S_ISDIR(st.st_mode)) {
ARROW_UNUSED(FileClose(fd));
return Status::IOError("Cannot open for reading: path '", file_name.ToString(),
"' is a directory");
}
}
#endif
return CheckFileOpResult(fd, errno_actual, file_name, "open local");
}
Result<int> FileOpenWritable(const PlatformFilename& file_name, bool write_only,
bool truncate, bool append) {
int fd, errno_actual;
#if defined(_WIN32)
SetLastError(0);
int oflag = _O_CREAT | _O_BINARY | _O_NOINHERIT;
DWORD desired_access = GENERIC_WRITE;
DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
DWORD creation_disposition = OPEN_ALWAYS;
if (append) {
oflag |= _O_APPEND;
}
if (truncate) {
oflag |= _O_TRUNC;
creation_disposition = CREATE_ALWAYS;
}
if (write_only) {
oflag |= _O_WRONLY;
} else {
oflag |= _O_RDWR;
desired_access |= GENERIC_READ;
}
HANDLE file_handle =
CreateFileW(file_name.ToNative().c_str(), desired_access, share_mode, NULL,
creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD last_error = GetLastError();
if (last_error == ERROR_SUCCESS || last_error == ERROR_ALREADY_EXISTS) {
errno_actual = 0;
fd = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle), oflag);
} else {
return IOErrorFromWinError(last_error, "Failed to open local file '",
file_name.ToString(), "'");
}
#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;
}
fd = open(file_name.ToNative().c_str(), oflag, ARROW_WRITE_SHMODE);
errno_actual = errno;
#endif
RETURN_NOT_OK(CheckFileOpResult(fd, errno_actual, file_name, "open local"));
if (append) {
// Seek to end, as O_APPEND does not necessarily do it
auto ret = lseek64_compat(fd, 0, SEEK_END);
if (ret == -1) {
ARROW_UNUSED(FileClose(fd));
return Status::IOError("lseek failed");
}
}
return fd;
}
Result<int64_t> FileTell(int fd) {
int64_t current_pos;
#if defined(_WIN32)
current_pos = _telli64(fd);
if (current_pos == -1) {
return Status::IOError("_telli64 failed");
}
#else
current_pos = lseek64_compat(fd, 0, SEEK_CUR);
CHECK_LSEEK(current_pos);
#endif
return current_pos;
}
Result<Pipe> CreatePipe() {
int ret;
int fd[2];
#if defined(_WIN32)
ret = _pipe(fd, 4096, _O_BINARY);
#else
ret = pipe(fd);
#endif
if (ret == -1) {
return IOErrorFromErrno(errno, "Error creating pipe");
}
return Pipe{fd[0], fd[1]};
}
static Status StatusFromMmapErrno(const char* prefix) {
#ifdef _WIN32
errno = __map_mman_error(GetLastError(), EPERM);
#endif
return IOErrorFromErrno(errno, prefix);
}
//
// 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");