forked from RPCS3/rpcs3
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFile.cpp
More file actions
3215 lines (2643 loc) · 69.6 KB
/
Copy pathFile.cpp
File metadata and controls
3215 lines (2643 loc) · 69.6 KB
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
#include "File.h"
#include "mutex.h"
#include "StrFmt.h"
#include <span>
#include <unordered_map>
#include <algorithm>
#include <cstring>
#include <map>
#include <iostream>
#include "util/asm.hpp"
#include "util/coro.hpp"
using namespace std::literals::string_literals;
#ifdef ANDROID
std::string g_android_executable_dir;
std::string g_android_config_dir;
std::string g_android_cache_dir;
#endif
#ifdef _WIN32
#include "Utilities/StrUtil.h"
#include <cwchar>
#include <Windows.h>
#include <winioctl.h>
static std::unique_ptr<wchar_t[]> to_wchar(std::string_view source)
{
// String size + null terminator
const usz buf_size = source.size() + 1;
// Safe size
const int size = narrow<int>(buf_size);
// Buffer for max possible output length
std::unique_ptr<wchar_t[]> buffer(new wchar_t[buf_size + 8 + 32768]);
// If path points to an optical raw device, copy it AS IS
if (fs::is_optical_raw_device(std::string(source)))
{
ensure(MultiByteToWideChar(CP_UTF8, 0, source.data(), size, buffer.get() + 32768, size)); // "to_wchar"
// Canonicalize wide path (replace '/', ".", "..", \\ repetitions, etc)
ensure(GetFullPathNameW(buffer.get() + 32768, 32768, buffer.get(), nullptr) - 1 < 32768 - 1); // "to_wchar"
return buffer;
}
// Prepend wide path prefix (4 characters)
std::memcpy(buffer.get() + 32768, L"\\\\\?\\", 4 * sizeof(wchar_t));
// Test whether additional UNC prefix is required
const bool unc = source.size() > 2 && (source[0] == '\\' || source[0] == '/') && source[1] == source[0];
if (unc)
{
// Use \\?\UNC\ prefix
std::memcpy(buffer.get() + 32768 + 4, L"UNC\\", 4 * sizeof(wchar_t));
}
ensure(MultiByteToWideChar(CP_UTF8, 0, source.data(), size, buffer.get() + 32768 + (unc ? 8 : 4), size)); // "to_wchar"
// Canonicalize wide path (replace '/', ".", "..", \\ repetitions, etc)
ensure(GetFullPathNameW(buffer.get() + 32768, 32768, buffer.get(), nullptr) - 1 < 32768 - 1); // "to_wchar"
return buffer;
}
static time_t to_time(const ULARGE_INTEGER& ft)
{
return ft.QuadPart / 10000000ULL - 11644473600ULL;
}
static time_t to_time(const LARGE_INTEGER& ft)
{
ULARGE_INTEGER v;
v.LowPart = ft.LowPart;
v.HighPart = ft.HighPart;
return to_time(v);
}
static time_t to_time(const FILETIME& ft)
{
ULARGE_INTEGER v;
v.LowPart = ft.dwLowDateTime;
v.HighPart = ft.dwHighDateTime;
return to_time(v);
}
static FILETIME from_time(s64 _time)
{
FILETIME result;
if (_time <= -11644473600ll)
{
result.dwLowDateTime = 0;
result.dwHighDateTime = 0;
}
else if (_time > s64{smax} / 10000000ll - 11644473600ll)
{
result.dwLowDateTime = 0xffffffff;
result.dwHighDateTime = 0x7fffffff;
}
else
{
const ullong wtime = (_time + 11644473600ull) * 10000000ull;
result.dwLowDateTime = static_cast<DWORD>(wtime);
result.dwHighDateTime = static_cast<DWORD>(wtime >> 32);
}
return result;
}
static fs::error to_error(DWORD e)
{
switch (e)
{
case ERROR_FILE_NOT_FOUND: return fs::error::noent;
case ERROR_PATH_NOT_FOUND: return fs::error::noent;
case ERROR_ACCESS_DENIED: return fs::error::acces;
case ERROR_ALREADY_EXISTS: return fs::error::exist;
case ERROR_FILE_EXISTS: return fs::error::exist;
case ERROR_NEGATIVE_SEEK: return fs::error::inval;
case ERROR_DIRECTORY: return fs::error::inval;
case ERROR_INVALID_NAME: return fs::error::inval;
case ERROR_INVALID_FUNCTION: return fs::error::inval;
case ERROR_SHARING_VIOLATION: return fs::error::acces;
case ERROR_DIR_NOT_EMPTY: return fs::error::notempty;
case ERROR_NOT_READY: return fs::error::noent;
case ERROR_FILENAME_EXCED_RANGE: return fs::error::toolong;
case ERROR_DISK_FULL: return fs::error::nospace;
case ERROR_NOT_SAME_DEVICE: return fs::error::xdev;
default: return fs::error::unknown;
}
}
#else
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/statvfs.h>
#include <sys/file.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <dirent.h>
#include <fcntl.h>
#include <libgen.h>
#include <string.h>
#include <unistd.h>
#include <utime.h>
#if defined(__APPLE__)
#include <copyfile.h>
#include <mach-o/dyld.h>
#include <limits.h>
#include <sys/disk.h>
#include <sys/param.h>
#include <sys/mount.h>
#elif defined(__linux__) || defined(__sun)
#include <sys/sendfile.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <linux/fs.h>
#else
#include <fstream>
#include <sys/disk.h>
#include <sys/param.h>
#include <sys/mount.h>
#endif
static fs::error to_error(int e)
{
switch (e)
{
case ENOENT: return fs::error::noent;
case EEXIST: return fs::error::exist;
case EINVAL: return fs::error::inval;
case EACCES: return fs::error::acces;
case ENOTEMPTY: return fs::error::notempty;
case EROFS: return fs::error::readonly;
case EISDIR: return fs::error::isdir;
case ENOTDIR: return fs::error::notdir;
case ENOSPC: return fs::error::nospace;
case EXDEV: return fs::error::xdev;
default: return fs::error::unknown;
}
}
#if defined(__linux__)
// Major numbers of the block devices an optical disc can be accessed through (see "Documentation/admin-guide/devices.txt")
constexpr unsigned int s_scsi_cdrom_major = 11; // Optical drive (e.g. "/dev/sr0")
constexpr unsigned int s_loopback_major = 7; // Disc image attached with "mount"/"losetup" (e.g. "/dev/loop0")
#endif
// Check whether the provided device node is an optical drive (e.g. a Blu-Ray Disc drive) or a mounted disc image
static bool is_optical_device_node(const struct ::stat& file_info)
{
#if defined(__linux__)
// An optical drive is exposed as a block device using the SCSI CD-ROM major number (e.g. "/dev/sr0", "/dev/scd0" or the "/dev/cdrom" link).
// A disc image attached through "mount -o loop" (or "losetup") is exposed as a loopback block device instead (e.g. "/dev/loop0"):
// it is the counterpart of an ISO file mounted on Windows, where the resulting virtual drive is reported as DRIVE_CDROM
if (!S_ISBLK(file_info.st_mode))
{
return false;
}
const unsigned int device_major = major(file_info.st_rdev);
return device_major == s_scsi_cdrom_major || device_major == s_loopback_major;
#elif defined(__APPLE__)
// The raw (unbuffered) device is a character device (e.g. "/dev/rdisk2").
// NOTE: there is no cheap way to tell an optical drive from any other raw disk here, so any raw disk node is accepted
return S_ISCHR(file_info.st_mode);
#else
// On the BSDs an optical drive is a character device (e.g. "/dev/cd0")
return S_ISCHR(file_info.st_mode) || S_ISBLK(file_info.st_mode);
#endif
}
// Check whether the path is the root of a mounted filesystem (e.g. the mount point of a disc): "st_dev" changes when crossing a mount point
[[maybe_unused]] static bool is_mount_point(const std::string& path, const struct ::stat& file_info)
{
// A file is never a mount point: discard it without any syscall (the "stat()" below would fail with ENOTDIR anyway)
if (!S_ISDIR(file_info.st_mode))
{
return false;
}
struct ::stat parent_info;
if (::stat((path + "/..").c_str(), &parent_info) != 0)
{
return false;
}
return parent_info.st_dev != file_info.st_dev;
}
// Retrieve the size of a raw device: "fstat()" reports no size (0) on such a device
static u64 get_raw_device_size(int fd)
{
#if defined(__linux__)
if (u64 size = 0; ::ioctl(fd, BLKGETSIZE64, &size) == 0)
{
return size;
}
#elif defined(__APPLE__)
u64 block_count = 0;
u32 block_size = 0;
if (::ioctl(fd, DKIOCGETBLOCKCOUNT, &block_count) == 0 && ::ioctl(fd, DKIOCGETBLOCKSIZE, &block_size) == 0)
{
return block_count * block_size;
}
#elif defined(__FreeBSD__) || defined(__DragonFly__)
if (off_t media_size = 0; ::ioctl(fd, DIOCGMEDIASIZE, &media_size) == 0)
{
return static_cast<u64>(media_size);
}
#endif
// Fallback: seek to the end of the device (restoring the current position afterwards)
const off_t old_pos = ::lseek(fd, 0, SEEK_CUR);
const off_t end_pos = ::lseek(fd, 0, SEEK_END);
if (old_pos >= 0)
{
::lseek(fd, old_pos, SEEK_SET);
}
return end_pos > 0 ? static_cast<u64>(end_pos) : 0;
}
#endif
static std::string path_append(std::string_view path, std::string_view more)
{
std::string result;
if (const usz src_slash_pos = path.find_last_not_of('/'); src_slash_pos != path.npos)
{
path.remove_suffix(path.length() - src_slash_pos - 1);
result = path;
}
result.push_back('/');
if (const usz dst_slash_pos = more.find_first_not_of('/'); dst_slash_pos != more.npos)
{
more.remove_prefix(dst_slash_pos);
result.append(more);
}
return result;
}
namespace fs
{
thread_local error g_tls_error = error::ok;
class device_manager final
{
mutable shared_mutex m_mutex{};
std::unordered_map<std::string, shared_ptr<device_base>> m_map{};
public:
shared_ptr<device_base> get_device(const std::string& path);
shared_ptr<device_base> set_device(const std::string& name, shared_ptr<device_base>);
};
static device_manager& get_device_manager()
{
// Use magic static
static device_manager instance;
return instance;
}
file_base::~file_base()
{
}
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4646)
#endif
[[noreturn]] stat_t file_base::get_stat()
{
fmt::throw_exception("fs::file::get_stat() not supported.");
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
void file_base::sync()
{
// Do notning
}
fs::native_handle fs::file_base::get_handle()
{
#ifdef _WIN32
return INVALID_HANDLE_VALUE;
#else
return -1;
#endif
}
file_id file_base::get_id()
{
return {};
}
u64 file_base::write_gather(const iovec_clone* buffers, u64 buf_count)
{
u64 total = 0;
for (u64 i = 0; i < buf_count; i++)
{
if (!buffers[i].iov_base || buffers[i].iov_len + total < total)
{
g_tls_error = error::inval;
return -1;
}
total += buffers[i].iov_len;
}
const auto buf = std::make_unique<uchar[]>(total);
u64 copied = 0;
for (u64 i = 0; i < buf_count; i++)
{
std::memcpy(buf.get() + copied, buffers[i].iov_base, buffers[i].iov_len);
copied += buffers[i].iov_len;
}
return this->write(buf.get(), total);
}
file_id::operator bool() const
{
return !type.empty() && !data.empty();
}
// Test if identical
// For example: when LHS writes one byte to a file at X offset, RHS file be able to read that exact byte at X offset)
bool file_id::is_mirror_of(const file_id& rhs) const
{
// If either is an invalid ID we cannot compare safely, return false
return rhs && type == rhs.type && data == rhs.data;
}
// Test if both files point to the same file
// For example: if a file descriptor pointing to the complete file exists and is being truncated to 0 bytes from non-
// -zero size state: this has to affect both RHS and LHS files.
bool file_id::is_coherent_with(const file_id& rhs) const
{
struct id_view
{
std::string_view type_view;
std::span<const u8> data_view;
};
id_view _rhs{rhs.type, {rhs.data.data(), rhs.data.size()}};
id_view _lhs{type, {data.data(), data.size()}};
// Peek through fs::file wrappers
auto peek_wrapppers = [](id_view& id)
{
u64 offset_count = 0;
constexpr auto lv2_view = "lv2_file::file_view: "sv;
for (usz pos = 0; (pos = id.type_view.find(lv2_view, pos)) != umax; pos += lv2_view.size())
{
offset_count++;
}
// Remove offsets data
id.data_view = id.data_view.subspan(sizeof(u64) * offset_count);
// Get last category identifier
if (usz sep = id.type_view.rfind(": "); sep != umax)
{
id.type_view.remove_prefix(sep + 2);
}
};
peek_wrapppers(_rhs);
peek_wrapppers(_lhs);
// If either is an invalid ID we cannot compare safely, return false
if (_rhs.type_view.empty() || _rhs.data_view.empty())
{
return false;
}
return _rhs.type_view == _lhs.type_view && std::equal(_rhs.data_view.begin(), _rhs.data_view.end(), _lhs.data_view.begin(), _lhs.data_view.end());
}
dir_base::~dir_base()
{
}
device_base::device_base()
: fs_prefix(fmt::format("/vfsv0_%s%s_", fmt::base57(reinterpret_cast<u64>(this)), fmt::base57(utils::get_unique_tsc())))
{
}
device_base::~device_base()
{
}
bool device_base::remove_dir(const std::string&)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::create_dir(const std::string&)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::create_symlink(const std::string&)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::rename(const std::string&, const std::string&)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::remove(const std::string&)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::trunc(const std::string&, u64)
{
g_tls_error = error::readonly;
return false;
}
bool device_base::utime(const std::string&, s64, s64)
{
g_tls_error = error::readonly;
return false;
}
#ifdef _WIN32
class windows_file final : public file_base
{
HANDLE m_handle;
bool m_raw_device;
atomic_t<u64> m_pos {0};
public:
windows_file(HANDLE handle, bool raw_device = false)
: m_handle(handle), m_raw_device(raw_device)
{
}
~windows_file() override
{
if (m_handle != nullptr)
{
CloseHandle(m_handle);
}
}
stat_t get_stat() override
{
FILE_BASIC_INFO basic_info {};
ensure(GetFileInformationByHandleEx(m_handle, FileBasicInfo, &basic_info, sizeof(FILE_BASIC_INFO))); // "file::stat"
stat_t info {};
info.is_directory = (basic_info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
info.is_writable = (basic_info.FileAttributes & FILE_ATTRIBUTE_READONLY) == 0;
info.size = this->size();
info.atime = to_time(basic_info.LastAccessTime);
info.mtime = to_time(basic_info.LastWriteTime);
info.ctime = info.mtime;
if (info.atime < info.mtime)
info.atime = info.mtime;
return info;
}
void sync() override
{
ensure(FlushFileBuffers(m_handle)); // "file::sync"
}
bool trunc(u64 length) override
{
FILE_END_OF_FILE_INFO _eof {};
_eof.EndOfFile.QuadPart = length;
if (!SetFileInformationByHandle(m_handle, FileEndOfFileInfo, &_eof, sizeof(_eof)))
{
g_tls_error = to_error(GetLastError());
return false;
}
return true;
}
u64 read(void* buffer, u64 count) override
{
u64 nread_sum = 0;
for (char* data = static_cast<char*>(buffer); count;)
{
const DWORD size = static_cast<DWORD>(std::min<u64>(count, DWORD{umax} & -4096));
DWORD nread = 0;
OVERLAPPED ovl{};
const u64 pos = m_pos;
ovl.Offset = DWORD(pos);
ovl.OffsetHigh = DWORD(pos >> 32);
ensure(ReadFile(m_handle, data, size, &nread, &ovl) || GetLastError() == ERROR_HANDLE_EOF); // "file::read"
nread_sum += nread;
m_pos += nread;
if (nread < size)
{
break;
}
count -= size;
data += size;
}
return nread_sum;
}
u64 read_at(u64 offset, void* buffer, u64 count) override
{
u64 nread_sum = 0;
for (char* data = static_cast<char*>(buffer); count;)
{
const DWORD size = static_cast<DWORD>(std::min<u64>(count, DWORD{umax} & -4096));
DWORD nread = 0;
OVERLAPPED ovl{};
ovl.Offset = DWORD(offset);
ovl.OffsetHigh = DWORD(offset >> 32);
ensure(ReadFile(m_handle, data, size, &nread, &ovl) || GetLastError() == ERROR_HANDLE_EOF); // "file::read"
nread_sum += nread;
if (nread < size)
{
break;
}
count -= size;
data += size;
offset += size;
}
return nread_sum;
}
u64 write(const void* buffer, u64 count) override
{
u64 nwritten_sum = 0;
for (const char* data = static_cast<const char*>(buffer); count;)
{
const DWORD size = static_cast<DWORD>(std::min<u64>(count, DWORD{umax} & -4096));
DWORD nwritten = 0;
OVERLAPPED ovl{};
const u64 pos = m_pos.fetch_add(size);
ovl.Offset = DWORD(pos);
ovl.OffsetHigh = DWORD(pos >> 32);
ensure(WriteFile(m_handle, data, size, &nwritten, &ovl)); // "file::write"
ensure(nwritten == size);
nwritten_sum += nwritten;
if (nwritten < size)
{
break;
}
count -= size;
data += size;
}
return nwritten_sum;
}
u64 seek(s64 offset, seek_mode whence) override
{
if (whence > seek_end)
{
fmt::throw_exception("Invalid whence (0x%x)", whence);
}
const s64 new_pos =
whence == fs::seek_set ? offset :
whence == fs::seek_cur ? offset + m_pos :
whence == fs::seek_end ? offset + size() : -1;
if (new_pos < 0)
{
fs::g_tls_error = fs::error::inval;
return -1;
}
m_pos = new_pos;
return m_pos;
}
u64 size() override
{
if (m_raw_device)
{
// For a raw device, we need to use DeviceIoControl.
DISK_GEOMETRY_EX geometry;
ensure(DeviceIoControl(m_handle, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, nullptr, 0, &geometry, sizeof(geometry), nullptr, nullptr));
return geometry.DiskSize.QuadPart;
}
// NOTE: this can fail if we access a mounted empty drive (e.g. after unmounting an iso).
LARGE_INTEGER size;
ensure(GetFileSizeEx(m_handle, &size)); // "file::size"
return size.QuadPart;
}
native_handle get_handle() override
{
return m_handle;
}
file_id get_id() override
{
file_id id{"windows_file"};
id.data.resize(sizeof(FILE_ID_INFO));
FILE_ID_INFO info {};
if (!GetFileInformationByHandleEx(m_handle, FileIdInfo, &info, sizeof(info)))
{
// Try GetFileInformationByHandle as a fallback
BY_HANDLE_FILE_INFORMATION info2{};
ensure(GetFileInformationByHandle(m_handle, &info2));
info = {};
info.VolumeSerialNumber = info2.dwVolumeSerialNumber;
std::memcpy(&info.FileId, &info2.nFileIndexHigh, 8);
}
std::memcpy(id.data.data(), &info, sizeof(info));
return id;
}
void release() override
{
m_handle = nullptr;
}
};
#else
class unix_file final : public file_base
{
int m_fd;
bool m_raw_device;
public:
unix_file(int fd, bool raw_device = false)
: m_fd(fd), m_raw_device(raw_device)
{
}
~unix_file() override
{
if (m_fd >= 0)
{
::close(m_fd);
}
}
stat_t get_stat() override
{
struct ::stat file_info;
ensure(::fstat(m_fd, &file_info) == 0); // "file::stat"
stat_t info {};
info.is_directory = S_ISDIR(file_info.st_mode);
info.is_writable = !m_raw_device && (file_info.st_mode & 0200); // HACK: approximation
info.size = m_raw_device ? get_raw_device_size(m_fd) : file_info.st_size; // A raw device reports no size through "fstat()"
info.atime = file_info.st_atime;
info.mtime = file_info.st_mtime;
info.ctime = info.mtime;
if (info.atime < info.mtime)
info.atime = info.mtime;
return info;
}
void sync() override
{
ensure(::fsync(m_fd) == 0); // "file::sync"
}
bool trunc(u64 length) override
{
if (::ftruncate(m_fd, length) != 0)
{
g_tls_error = to_error(errno);
return false;
}
return true;
}
u64 read(void* buffer, u64 count) override
{
u64 result = 0;
// Loop because (huge?) read can be processed partially
while (auto r = ::read(m_fd, buffer, count))
{
ensure(r > 0); // "file::read"
count -= r;
result += r;
buffer = static_cast<u8*>(buffer) + r;
if (!count)
break;
}
return result;
}
u64 read_at(u64 offset, void* buffer, u64 count) override
{
u64 result = 0;
// For safety; see read()
while (auto r = ::pread(m_fd, buffer, count, offset))
{
ensure(r > 0); // "file::read_at"
count -= r;
offset += r;
result += r;
buffer = static_cast<u8*>(buffer) + r;
if (!count)
break;
}
return result;
}
u64 write(const void* buffer, u64 count) override
{
u64 result = 0;
// For safety; see read()
while (auto r = ::write(m_fd, buffer, count))
{
ensure(r > 0); // "file::write"
count -= r;
result += r;
buffer = static_cast<const u8*>(buffer) + r;
if (!count)
break;
}
return result;
}
u64 seek(s64 offset, seek_mode whence) override
{
if (whence > seek_end)
{
fmt::throw_exception("Invalid whence (0x%x)", whence);
}
const int mode =
whence == seek_set ? SEEK_SET :
whence == seek_cur ? SEEK_CUR : SEEK_END;
const auto result = ::lseek(m_fd, offset, mode);
if (result == -1)
{
g_tls_error = to_error(errno);
return -1;
}
return result;
}
u64 size() override
{
if (m_raw_device)
{
// For a raw device, we need to use an ioctl ("fstat()" would always report a null size)
return get_raw_device_size(m_fd);
}
struct ::stat file_info;
ensure(::fstat(m_fd, &file_info) == 0); // "file::size"
return file_info.st_size;
}
native_handle get_handle() override
{
return m_fd;
}
file_id get_id() override
{
struct ::stat file_info;
ensure(::fstat(m_fd, &file_info) == 0); // "file::get_id"
file_id id{"unix_file"};
id.data.resize(sizeof(file_info.st_dev) + sizeof(file_info.st_ino));
std::memcpy(id.data.data(), &file_info.st_dev, sizeof(file_info.st_dev));
std::memcpy(id.data.data() + sizeof(file_info.st_dev), &file_info.st_ino, sizeof(file_info.st_ino));
return id;
}
u64 write_gather(const iovec_clone* buffers, u64 buf_count) override
{
static_assert(sizeof(iovec) == sizeof(iovec_clone), "Weird iovec size");
static_assert(offsetof(iovec, iov_len) == offsetof(iovec_clone, iov_len), "Weird iovec::iov_len offset");
u64 result = 0;
while (buf_count)
{
iovec arg[256];
const auto count = std::min<u64>(buf_count, 256);
std::memcpy(&arg, buffers, sizeof(iovec) * count);
const auto added = ::writev(m_fd, arg, count);
ensure(added != -1); // "file::write_gather"
result += added;
buf_count -= count;
buffers += count;
}
return result;
}
void release() override
{
m_fd = -1;
}
};
#endif
}
shared_ptr<fs::device_base> fs::device_manager::get_device(const std::string& path)
{
reader_lock lock(m_mutex);
const usz prefix = path.find_first_of('_', 7) + 1;
const auto found = m_map.find(path.substr(prefix, path.find_first_of('/', 1) - prefix));
if (found == m_map.end() || !path.starts_with(found->second->fs_prefix))
{
return null_ptr;
}
return found->second;
}
shared_ptr<fs::device_base> fs::device_manager::set_device(const std::string& name, shared_ptr<device_base> device)
{
std::lock_guard lock(m_mutex);
if (device)
{
// Adding
if (auto [it, ok] = m_map.try_emplace(name, std::move(device)); ok)
{
return it->second;
}
g_tls_error = error::exist;
}
else
{
// Removing
if (auto found = m_map.find(name); found != m_map.end())
{
device = std::move(found->second);
m_map.erase(found);
return device;
}
g_tls_error = error::noent;
}
return null_ptr;
}
shared_ptr<fs::device_base> fs::get_virtual_device(const std::string& path)
{
// Every virtual device path must have specific name at the beginning
if (path.starts_with("/vfsv0_") && path.size() >= 8 + 22 && path[29] == '_' && path.find_first_of('/', 1) > 29)
{
return get_device_manager().get_device(path);
}
return null_ptr;
}
shared_ptr<fs::device_base> fs::set_virtual_device(const std::string& name, shared_ptr<device_base> device)
{
return get_device_manager().set_device(name, std::move(device));
}
std::string_view fs::get_parent_dir_view(std::string_view path, u32 parent_level)
{
std::string_view result = path;
// Number of path components to remove
usz to_remove = parent_level;
while (to_remove--)
{
// Trim contiguous delimiters at the end
if (usz sz = result.find_last_not_of(delim) + 1)
{
result = result.substr(0, sz);
}
else
{
return "/";
}
const auto elem = result.substr(result.find_last_of(delim) + 1);
if (elem.empty() || elem.size() == result.size())
{
break;