Repository navigation
Expand file tree
/
Copy pathKernelFileSystemTests.cpp
More file actions
1391 lines (1319 loc) · 70.3 KB
/
Copy pathKernelFileSystemTests.cpp
File metadata and controls
1391 lines (1319 loc) · 70.3 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 <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include "common/emulatorConfig.h"
#include "common/archive.h"
#include "common/file.h"
#include "ArchiveTestFixture.h"
#include "common/logging/log.h"
#include "common/subsystems.h"
#include "common/threads.h"
#include "common/stringUtils.h"
#include "graphics/presentation/window/windowInternal.h"
#include "kernel/eventQueue.h"
#include "kernel/fileSystem.h"
#include "libs/errno.h"
#include "libs/network.h"
#include "loader/symbolDatabase.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <future>
#include <limits>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#if defined(__linux__)
#include <sys/mman.h>
#include <unistd.h>
#endif
namespace Libs::LibKernelApr {
void InitLibKernel_1_Apr(Loader::SymbolDatabase *symbols);
}
namespace Libs {
void InitLibKernel_1(Loader::SymbolDatabase *symbols);
}
namespace Libs::LibAmpr {
void InitAmpr_1(Loader::SymbolDatabase *symbols);
}
namespace Libs::LibNet {
void InitNet_1_Net(Loader::SymbolDatabase *symbols);
}
namespace Libs::LibNpWebApi2 {
void InitNet_1_NpWebApi2(Loader::SymbolDatabase *symbols);
}
namespace {
namespace FileSystem = Libs::LibKernel::FileSystem;
void Check(bool value, const char *text) {
if (!value) {
std::fprintf(stderr, "KernelFileSystemTests: failed: %s\n", text);
std::abort();
}
}
class TempDirectory {
public:
TempDirectory() {
const auto unique =
std::chrono::steady_clock::now().time_since_epoch().count();
m_path = std::filesystem::temp_directory_path() /
("kyty_kernel_file_system_" + std::to_string(unique));
Check(std::filesystem::create_directories(m_path),
"create temporary directory");
}
~TempDirectory() {
std::error_code error;
std::filesystem::remove_all(m_path, error);
}
[[nodiscard]] const std::filesystem::path &Path() const { return m_path; }
KYTY_CLASS_NO_COPY(TempDirectory);
private:
std::filesystem::path m_path;
};
void CheckSaveRename(const std::filesystem::path &root,
std::string_view payload) {
constexpr char Source[] = "/savedata0/STEMP000.DAT";
constexpr char Target[] = "/savedata0/SDATA000.DAT";
constexpr char Suffix[] = "-after-rename";
const int fd = FileSystem::KernelOpen(Source, 0x601, 0777);
Check(fd >= 3, "open temporary save file");
Check(FileSystem::KernelWrite(fd, payload.data(), payload.size()) ==
payload.size(),
"write save payload");
Check(FileSystem::KernelRename(Source, Target) == OK,
"rename open save file");
Check(FileSystem::KernelWrite(fd, Suffix, sizeof(Suffix) - 1) ==
sizeof(Suffix) - 1,
"write through renamed descriptor");
Check(FileSystem::KernelClose(fd) == OK, "close renamed descriptor");
Common::File result(root / "SDATA000.DAT", Common::File::Mode::Read);
Check(!result.IsInvalid(), "open renamed save file");
const auto data = result.ReadWholeBuffer();
const std::string expected = std::string(payload) + Suffix;
Check(data.size() == expected.size(), "renamed save size");
Check(std::memcmp(data.data(), expected.data(), expected.size()) == 0,
"renamed save contents");
}
void TestSaveOpenVisibility() {
constexpr char Path[] = "/savedata0/visible-save.dat";
constexpr char Payload[] = "saved progress";
const int fd = FileSystem::KernelOpen(Path, 0xa01, 0777);
Check(fd >= 3, "create save file exclusively");
FileSystem::FileStat stat {};
Check(FileSystem::KernelStat(Path, &stat) == OK && stat.st_size == 0,
"created save file is visible before close");
Check(FileSystem::KernelOpen(Path, 0xa01, 0777) ==
Libs::LibKernel::KERNEL_ERROR_EEXIST,
"exclusive creation detects an open save file");
Check(FileSystem::KernelWrite(fd, Payload, sizeof(Payload) - 1) ==
sizeof(Payload) - 1,
"populate save file before truncation");
Check(FileSystem::KernelClose(fd) == OK, "close populated save file");
Check(FileSystem::KernelStat(Path, &stat) == OK &&
stat.st_size == sizeof(Payload) - 1,
"save file contains the truncation fixture");
const int truncated = FileSystem::KernelOpen(Path, 0x401, 0777);
Check(truncated >= 3, "truncate existing save file");
Check(FileSystem::KernelStat(Path, &stat) == OK && stat.st_size == 0,
"save truncation is visible before close");
Check(FileSystem::KernelClose(truncated) == OK, "close truncated save file");
}
void TestAioBatches() {
namespace Kernel = Libs::LibKernel;
Loader::SymbolDatabase symbols;
Libs::InitLibKernel_1(&symbols);
const auto find = [&](const char *nid) {
const auto *symbol = symbols.FindByNid(nid, Loader::SymbolType::Func);
Check(symbol != nullptr, "AIO exports resolve");
return symbol->vaddr;
};
struct Result { int64_t return_value; uint32_t state; };
struct Request {
int64_t offset;
size_t size;
void *buffer;
Result *result;
int32_t fd;
};
using Submit = int (KYTY_SYSV_ABI *)(Request *, int32_t, int32_t, int32_t *);
using Batch = int (KYTY_SYSV_ABI *)(int32_t *, int32_t, int32_t *);
using Single = int (KYTY_SYSV_ABI *)(int32_t, int32_t *);
using Wait = int (KYTY_SYSV_ABI *)(int32_t, int32_t *, uint32_t *);
using WaitBatch = int (KYTY_SYSV_ABI *)(int32_t *, int32_t, int32_t *, uint32_t, uint32_t *);
const auto submit = reinterpret_cast<Submit>(find("HgX7+AORI58"));
const auto poll = reinterpret_cast<Batch>(find("o7O4z3jwKzo"));
const auto erase = reinterpret_cast<Batch>(find("Ft3EtsZzAoY"));
const auto poll_one = reinterpret_cast<Single>(find("2pOuoWoCxdk"));
const auto erase_one = reinterpret_cast<Single>(find("5TgME6AYty4"));
const auto wait = reinterpret_cast<Wait>(find("KOF-oJbQVvc"));
const auto wait_batch = reinterpret_cast<WaitBatch>(find("lgK+oIWkJyA"));
constexpr char Payload[] = "AIO payload";
const int fd = FileSystem::KernelOpen("/savedata0/aio.dat", 0x602, 0777);
Check(fd >= 3 && FileSystem::KernelWrite(fd, Payload, sizeof(Payload)) == sizeof(Payload),
"create AIO read fixture");
std::array<int32_t, 3> ids {};
std::array<char, 4> buffer {};
Result result {};
Request request {2, buffer.size(), buffer.data(), &result, fd};
for (int i = 0; i < 2; ++i) {
Check(submit(&request, 1, 2, &ids[i]) == OK &&
result.return_value == buffer.size() && result.state == 3 &&
std::memcmp(buffer.data(), Payload + 2, buffer.size()) == 0,
"AIO submission reads bytes at the requested offset");
}
ids[2] = -1;
std::array<int32_t, 3> states {-1, -1, -1};
uint32_t timeout = 0;
Check(wait_batch(ids.data(), ids.size(), states.data(), 2, &timeout) == OK &&
states[0] == 3 && states[1] == 3 && states[2] == Kernel::KERNEL_ERROR_ESRCH,
"OR wait observes completed reads and invalid-ID errors even with a zero timeout");
Check(poll_one(ids[0], &states[0]) == OK && states[0] == (3 | 0x10000) &&
poll(ids.data(), 2, states.data()) == OK &&
states[0] == (3 | 0x10000) && states[1] == (3 | 0x10000) &&
wait(ids[0], &states[0], nullptr) == OK && states[0] == (3 | 0x10000),
"single and batch polls and waits share completion notification state");
timeout = 1000000;
Check(wait_batch(ids.data(), ids.size(), states.data(), 1, &timeout) == OK &&
states[0] == (3 | 0x10000) && states[1] == (3 | 0x10000) &&
states[2] == Kernel::KERNEL_ERROR_ESRCH && timeout <= 1000000 &&
wait_batch(ids.data(), ids.size(), states.data(), 2, nullptr) == OK &&
wait_batch(ids.data(), 1, states.data(), 0, nullptr) == OK,
"AND and OR waits return when all IDs are terminal and one-ID waits ignore mode");
Check(erase(ids.data(), ids.size(), states.data()) == OK &&
states[0] == OK && states[1] == OK && states[2] == Kernel::KERNEL_ERROR_ESRCH,
"batch deletion writes per-request results");
Check(poll_one(ids[0], &states[0]) == OK && states[0] == Kernel::KERNEL_ERROR_ESRCH &&
erase_one(ids[1], &states[1]) == OK && states[1] == Kernel::KERNEL_ERROR_ESRCH,
"deleted AIO IDs are invalid for single-request APIs");
for (const auto batch : {poll, erase}) {
states.fill(42);
Check(batch(nullptr, 1, states.data()) == Kernel::KERNEL_ERROR_EFAULT &&
batch(ids.data(), 1, nullptr) == Kernel::KERNEL_ERROR_EFAULT &&
batch(ids.data(), 0, states.data()) == Kernel::KERNEL_ERROR_EINVAL &&
batch(ids.data(), 129, states.data()) == Kernel::KERNEL_ERROR_EINVAL &&
states == std::array<int32_t, 3> {42, 42, 42},
"invalid batch arguments do not modify outputs");
std::array<int32_t, 128> invalid_ids {};
std::array<int32_t, 128> errors {};
Check(batch(invalid_ids.data(), invalid_ids.size(), errors.data()) == OK &&
std::all_of(errors.begin(), errors.end(), [](int32_t error) {
return error == Kernel::KERNEL_ERROR_ESRCH;
}),
"maximum-sized batch returns all invalid-ID errors");
}
states.fill(42);
Check(wait_batch(nullptr, 1, states.data(), 1, nullptr) == Kernel::KERNEL_ERROR_EFAULT &&
wait_batch(ids.data(), 1, nullptr, 1, nullptr) == Kernel::KERNEL_ERROR_EFAULT &&
wait_batch(ids.data(), 0, states.data(), 1, nullptr) == Kernel::KERNEL_ERROR_EINVAL &&
wait_batch(ids.data(), 129, states.data(), 1, nullptr) == Kernel::KERNEL_ERROR_EINVAL &&
wait_batch(ids.data(), 2, states.data(), 0, nullptr) == Kernel::KERNEL_ERROR_EINVAL &&
wait_batch(ids.data(), 2, states.data(), 3, nullptr) == Kernel::KERNEL_ERROR_EINVAL &&
states == std::array<int32_t, 3> {42, 42, 42},
"invalid wait arguments do not modify outputs");
std::array<int32_t, 128> invalid_ids {};
std::array<int32_t, 128> errors {};
Check(wait_batch(invalid_ids.data(), invalid_ids.size(), errors.data(), 1, nullptr) == OK &&
std::all_of(errors.begin(), errors.end(), [](int32_t error) {
return error == Kernel::KERNEL_ERROR_ESRCH;
}),
"maximum-sized wait returns every invalid-ID error");
Check(FileSystem::KernelClose(fd) == OK, "close AIO read fixture");
}
void TestNpWebApi2Memory() {
Loader::SymbolDatabase symbols;
Libs::LibNpWebApi2::InitNet_1_NpWebApi2(&symbols);
const auto find = [&](const char *nid) {
const auto *symbol = symbols.FindByNid(nid, Loader::SymbolType::Func);
Check(symbol != nullptr, "NpWebApi2 library and memory exports resolve");
return symbol->vaddr;
};
struct Stats { size_t pool, maximum, current; int32_t reserved; };
static_assert(sizeof(Stats) == 32 && offsetof(Stats, reserved) == 24);
using Initialize = int (KYTY_SYSV_ABI *)(int, size_t);
using GetStats = int (KYTY_SYSV_ABI *)(int, Stats *);
using Terminate = int (KYTY_SYSV_ABI *)(int);
const auto initialize = reinterpret_cast<Initialize>(find("+o9816YQhqQ"));
const auto get_stats = reinterpret_cast<GetStats>(find("Xweb+naPZ8Y"));
const auto terminate = reinterpret_cast<Terminate>(find("bEvXpcEk200"));
const int first = initialize(1, 65537);
const int second = initialize(1, 16384);
Stats stats {1, 2, 3, 4};
Check(first > 0 && second > 0 && first != second &&
get_stats(first, &stats) == OK && stats.pool == 81920 &&
stats.maximum == 0 && stats.current == 0 && stats.reserved == 0 &&
get_stats(second, &stats) == OK && stats.pool == 16384,
"NpWebApi2 statistics retain each context's rounded pool capacity");
Check(get_stats(first, nullptr) == static_cast<int32_t>(0x80553402) &&
get_stats(0, &stats) == static_cast<int32_t>(0x80553403) &&
initialize(1, std::numeric_limits<size_t>::max()) == static_cast<int32_t>(0x80553402),
"NpWebApi2 statistics validate output, context ID, and pool rounding");
Check(terminate(first) == OK &&
get_stats(first, &stats) == static_cast<int32_t>(0x80553404) &&
terminate(first) == static_cast<int32_t>(0x80553404) &&
terminate(-1) == static_cast<int32_t>(0x80553403) &&
get_stats(second, &stats) == OK && stats.pool == 16384 &&
terminate(second) == OK,
"NpWebApi2 termination removes only the selected library context");
}
void CheckMountRoot(const std::filesystem::path &root) {
Common::File cache;
Check(cache.Create(root / "rpf.cache"), "create directory listing fixture");
cache.Close();
FileSystem::Mount(root, "/app0");
Check(FileSystem::GetRealFilename("/app0/rpf.cache") == root / "rpf.cache",
"resolve mount descendant");
Check(FileSystem::GetRealFilename("/app01/rpf.cache").empty(),
"mount prefix must end at a path component");
for (const char *path : {"/app0", "/app0/"}) {
for (const int flags : {0, 0x00020000}) {
const int fd = FileSystem::KernelOpen(path, flags, 0);
Check(fd >= 3, "open mounted root with O_RDONLY or O_DIRECTORY");
std::array<char, 512> entries {};
const int size = FileSystem::KernelGetdents(fd, entries.data(), entries.size());
Check(size > 0 && size <= entries.size(), "enumerate mounted root");
bool found = false;
for (int offset = 0; offset < size;) {
// Directory record: inode, record length, type, name length, name.
Check(size - offset >= 8, "directory record header fits");
uint16_t length = 0;
std::memcpy(&length, entries.data() + offset + 4, sizeof(length));
const auto name_length = static_cast<uint8_t>(entries[offset + 7]);
Check(length >= 8 + name_length + 1 && length <= size - offset,
"directory record and name fit");
if (std::string_view(entries.data() + offset + 8, name_length) == "rpf.cache") {
Check(entries[offset + 6] == 8, "cache directory entry is a regular file");
found = true;
}
offset += length;
}
Check(found, "mounted root listing contains rpf.cache");
Check(FileSystem::KernelClose(fd) == OK, "close mounted root");
}
}
FileSystem::Umount("/app0");
Check(FileSystem::GetRealFilename("/app0/rpf.cache").empty(),
"unmount by guest path");
for (const auto &folder : {root, root / ""}) {
for (const auto &host : {root, root / ""}) {
FileSystem::Mount(folder, "/app0");
FileSystem::Umount(Common::PathToGenericString(host));
Check(FileSystem::GetRealFilename("/app0/rpf.cache").empty(),
"unmount by host path with or without trailing separator");
}
}
}
void CheckUnmappedPaths(const std::filesystem::path &root) {
const auto host_file = root / "host-only.dat";
const auto host_path = Common::PathToGenericString(host_file);
Common::File fixture;
Check(fixture.Create(host_file), "create unmapped host file");
fixture.Close();
FileSystem::FileStat stat {};
Check(FileSystem::GetRealFilename(host_path).empty() &&
FileSystem::KernelOpen(host_path.c_str(), 0, 0) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelStat(host_path.c_str(), &stat) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelCheckReachability(host_path.c_str()) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT,
"existing host files are absent from the guest namespace");
Check(FileSystem::KernelUnlink(host_path.c_str()) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelRmdir(Common::PathToGenericString(root).c_str()) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
std::filesystem::exists(host_file),
"unmapped host files and directories cannot be removed");
const auto missing = Common::PathToGenericString(root / "unmapped-create");
Check(FileSystem::KernelOpen(missing.c_str(), 0x601, 0777) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelMkdir(missing.c_str(), 0777) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
!std::filesystem::exists(root / "unmapped-create"),
"creation requires a mounted guest destination");
FileSystem::Mount(root, "/app0");
Check(FileSystem::KernelRename("/app0/host-only.dat", missing.c_str()) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
std::filesystem::exists(host_file) &&
!std::filesystem::exists(root / "unmapped-create"),
"rename to an unmapped destination preserves the source");
FileSystem::Umount("/app0");
}
void CheckArchiveMount(const std::filesystem::path &root) {
const auto archive = root / u8"game-日本語.zar";
std::vector<uint8_t> payload(2 * 64 * 1024 + 33);
for (size_t i = 0; i < payload.size(); ++i) {
payload[i] = static_cast<uint8_t>(i * 37 + 11);
}
Check(ArchiveTests::CreateArchive(archive, payload), "create mounted archive fixture");
const auto archive_root = Common::MakeArchivePath(archive);
const auto host_member = archive_root / "assets/subdir/data.bin";
constexpr char GuestMember[] = "/app0/assets/subdir/data.bin";
FileSystem::Mount(archive_root, "/app0");
Check(FileSystem::GetRealFilename(GuestMember) == host_member &&
FileSystem::GetRealFilename("/app01/eboot.bin").empty(),
"resolve archive mounts at path-component boundaries");
Check(FileSystem::KernelOpen("/app0/../outside.bin", 0, 0) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelOpen("/app0/missing.bin", 0, 0) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT,
"reject traversal outside an archive and missing members");
FileSystem::FileStat path_stat{}, descriptor_stat{};
Check(FileSystem::KernelStat(GuestMember, &path_stat) == OK &&
path_stat.st_size == payload.size() &&
path_stat.st_size == Common::File::Size(host_member) &&
FileSystem::KernelCheckReachability(GuestMember) == OK,
"archive path stat and reachability agree with Common::File");
const int fd = FileSystem::KernelOpen("/app0/ASSETS/subdir/DATA.BIN", 0, 0);
Check(fd >= 3 && FileSystem::KernelFstat(fd, &descriptor_stat) == OK &&
descriptor_stat.st_size == path_stat.st_size &&
descriptor_stat.st_mode == path_stat.st_mode,
"case-insensitive archive open and descriptor stat agree");
std::array<uint8_t, 97> bytes{};
constexpr int64_t Offset = 64 * 1024 - 19;
Check(FileSystem::KernelPread(fd, bytes.data(), bytes.size(), Offset) == bytes.size() &&
std::equal(bytes.begin(), bytes.end(), payload.begin() + Offset) &&
FileSystem::KernelLseek(fd, 0, 1) == 0,
"archive pread crosses a compression block without moving position");
Check(FileSystem::KernelLseek(fd, Offset, 0) == Offset &&
FileSystem::KernelRead(fd, bytes.data(), bytes.size()) == bytes.size() &&
std::equal(bytes.begin(), bytes.end(), payload.begin() + Offset) &&
FileSystem::KernelLseek(fd, 0, 1) == Offset + bytes.size(),
"archive seek and sequential read share descriptor position");
Check(FileSystem::KernelLseek(fd, -9, 2) == payload.size() - 9 &&
FileSystem::KernelRead(fd, bytes.data(), bytes.size()) == 9 &&
std::equal(bytes.begin(), bytes.begin() + 9, payload.end() - 9) &&
FileSystem::KernelRead(fd, bytes.data(), bytes.size()) == 0,
"archive reads stop at the member boundary");
Check(FileSystem::KernelWrite(fd, bytes.data(), 1) ==
Libs::LibKernel::KERNEL_ERROR_EBADF &&
FileSystem::KernelPwrite(fd, bytes.data(), 1, 0) ==
Libs::LibKernel::KERNEL_ERROR_EBADF &&
FileSystem::KernelFtruncate(fd, 0) ==
Libs::LibKernel::KERNEL_ERROR_EBADF,
"archive read-only descriptors reject write and truncate");
const auto unicode_guest = std::string("/app0/") + std::string(ArchiveTests::UnicodeFilename);
const int unicode = FileSystem::KernelOpen(unicode_guest.c_str(), 0, 0);
Check(unicode >= 3 && FileSystem::KernelRead(unicode, bytes.data(), bytes.size()) ==
ArchiveTests::Eboot.size() &&
std::memcmp(bytes.data(), ArchiveTests::Eboot.data(), ArchiveTests::Eboot.size()) == 0,
"open and read a Unicode archive member");
Check(FileSystem::KernelClose(unicode) == OK, "close Unicode archive member");
const int directory = FileSystem::KernelOpen("/app0/", 0x00020000, 0);
Check(directory >= 3, "open mounted archive directory");
std::array<char, 512> block{};
const auto expected_entries = Common::File::GetDirEntries(archive_root);
size_t entries_seen = 0;
for (;;) {
const int length = FileSystem::KernelGetdents(directory, block.data(), block.size());
Check(length >= 0 && length <= block.size(), "read archive directory records");
if (length == 0) {
break;
}
for (size_t offset = 0; offset < static_cast<size_t>(length);) {
uint16_t record_length = 0;
Check(length - offset >= 8, "archive directory record header fits");
std::memcpy(&record_length, block.data() + offset + 4, sizeof(record_length));
const auto name_length = static_cast<uint8_t>(block[offset + 7]);
Check(record_length >= 9 + name_length && record_length <= length - offset,
"archive directory record fits");
const std::string_view name(block.data() + offset + 8, name_length);
Check(std::any_of(expected_entries.begin(), expected_entries.end(), [&](const auto &entry) {
return entry.name == name && block[offset + 6] == (entry.is_file ? 8 : 4);
}), "guest directory entry matches Common::File name and type");
++entries_seen;
offset += record_length;
}
}
Check(entries_seen == expected_entries.size(), "guest enumerates every archive directory entry");
Check(FileSystem::KernelClose(directory) == OK, "close archive directory");
for (const int flags : {1, 2, 0x0200, 0x0400}) {
Check(FileSystem::KernelOpen(GuestMember, flags, 0777) ==
Libs::LibKernel::KERNEL_ERROR_EROFS,
"archive rejects write, create and truncate open flags");
}
Check(FileSystem::KernelUnlink(GuestMember) == Libs::LibKernel::KERNEL_ERROR_EROFS &&
FileSystem::KernelMkdir("/app0/new-dir", 0777) == Libs::LibKernel::KERNEL_ERROR_EROFS &&
FileSystem::KernelRmdir("/app0/assets") == Libs::LibKernel::KERNEL_ERROR_EROFS &&
FileSystem::KernelRename(GuestMember, "/app0/renamed.bin") ==
Libs::LibKernel::KERNEL_ERROR_EROFS,
"archive mount rejects path mutations");
FileSystem::Umount("/app0");
Check(FileSystem::GetRealFilename(GuestMember).empty() &&
FileSystem::KernelOpen(GuestMember, 0, 0) == Libs::LibKernel::KERNEL_ERROR_ENOENT &&
FileSystem::KernelLseek(fd, 0, 0) == 0 &&
FileSystem::KernelRead(fd, bytes.data(), bytes.size()) == bytes.size() &&
std::equal(bytes.begin(), bytes.end(), payload.begin()),
"unmount hides archive paths while open descriptors retain the reader");
Check(FileSystem::KernelClose(fd) == OK, "close last archive descriptor");
}
void CheckUnicodePaths(const std::filesystem::path &root) {
constexpr std::string_view HostDirectory =
"Test\xc3\xa9-\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e";
constexpr std::string_view GuestFilename =
"asset-\xc3\xa9-\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e.bin";
const auto unicode_root =
root / Common::PathFromUtf8(HostDirectory);
const auto nested_root = unicode_root / "nested";
Check(Common::File::CreateDirectories(nested_root),
"create nested Unicode host directory");
CheckMountRoot(nested_root);
const auto native_file =
nested_root / Common::PathFromUtf8(GuestFilename);
Common::File fixture;
Check(fixture.Create(native_file), "create Unicode filename");
fixture.Close();
const auto entries = Common::File::GetDirEntries(nested_root);
Check(std::any_of(entries.begin(), entries.end(), [&](const auto &entry) {
return entry.is_file && entry.name == GuestFilename;
}), "directory enumeration returns UTF-8 filenames");
FileSystem::Mount(nested_root, "/app0");
const auto guest_file =
std::string("/app0/") + std::string(GuestFilename);
Check(FileSystem::GetRealFilename(guest_file) == native_file,
"resolve Unicode guest path");
const int fd = FileSystem::KernelOpen(guest_file.c_str(), 0, 0);
Check(fd >= 3, "open Unicode guest path");
Check(FileSystem::KernelClose(fd) == OK,
"close Unicode guest path");
FileSystem::Umount("/app0");
}
void CheckUnicodeLogPath(const std::filesystem::path &root) {
Config::ConfigOptions options;
options.printf_direction = Config::LogDirection::File;
options.printf_output_file = root / u8"logs-\u65e5\u672c\u8a9e-\U0001f600" / u8"log-\u00e9.txt";
Config::Load(options);
Log::Initialize();
constexpr std::string_view Payload = "Unicode log path\n";
Log::Write(Payload);
Log::Shutdown();
Common::File result(options.printf_output_file, Common::File::Mode::Read);
Check(!result.IsInvalid(), "open Unicode log file");
const auto data = result.ReadWholeBuffer();
Check(data.size() == Payload.size() &&
std::memcmp(data.data(), Payload.data(), data.size()) == 0,
"Unicode log file contains output");
options.printf_direction = Config::LogDirection::Silent;
Config::Load(options);
Log::Initialize();
}
void CheckDirectoryStream(const std::filesystem::path &root) {
const auto directory = root / "directory-stream";
Check(std::filesystem::create_directory(directory),
"create seek fixture directory");
for (int i = 0; i < 48; ++i) {
Common::File fixture;
Check(fixture.Create(directory / ("directory-entry-" + std::to_string(i))),
"create enough entries to cross directory blocks");
fixture.Close();
}
FileSystem::Mount(directory, "/app0");
const int fd = FileSystem::KernelOpen("/app0/", 0, 0);
Check(fd >= 3, "open directory as read-only asset");
const auto end = FileSystem::KernelLseek(fd, 0, 2);
Check(end > 512 && end % 512 == 0,
"directory SEEK_END uses padded stream size");
FileSystem::FileStat stat{};
Check(FileSystem::KernelFstat(fd, &stat) == OK && stat.st_size == end &&
stat.st_blksize == 512,
"directory stat agrees with seek and enumeration");
Check(FileSystem::KernelStat("/app0/", &stat) == OK && stat.st_size == end &&
stat.st_blocks == end / 512,
"path and descriptor directory stat agree");
Check(FileSystem::KernelLseek(fd, 0, 0) == 0,
"rewind directory for asset read");
std::vector<char> raw(static_cast<size_t>(end));
Check(FileSystem::KernelRead(fd, raw.data(), raw.size()) == end &&
FileSystem::KernelRead(fd, raw.data(), 1) == 0,
"raw directory read reaches EOF");
Check(FileSystem::KernelLseek(fd, -end, 1) == 0,
"directory SEEK_CUR uses the position advanced by read");
std::array<char, 512> block{};
int64_t base = -1;
for (int64_t offset = 0; offset < end; offset += block.size()) {
Check(FileSystem::KernelGetdirentries(fd, block.data(), block.size(),
&base) == block.size() &&
base == offset &&
std::memcmp(block.data(), raw.data() + offset, block.size()) == 0,
"directory enumeration shares raw bytes and reports each block "
"position");
for (size_t pos = 0; pos < block.size();) {
Check(block.size() - pos >= 8, "directory record header fits");
uint16_t length = 0;
std::memcpy(&length, block.data() + pos + 4, sizeof(length));
const auto name_length = static_cast<uint8_t>(block[pos + 7]);
Check(length >= 9 + name_length && length <= block.size() - pos &&
block[pos + 8 + name_length] == '\0',
"directory entries remain complete within every block");
pos += length;
}
}
Check(FileSystem::KernelGetdirentries(fd, block.data(), block.size(),
&base) == 0 &&
base == end,
"directory enumeration reports EOF position");
Check(FileSystem::KernelLseek(fd, 512, 0) == 512 &&
FileSystem::KernelGetdirentries(fd, block.data(), block.size(),
&base) == block.size() &&
base == 512 &&
std::memcmp(block.data(), raw.data() + 512, block.size()) == 0,
"restore and reread a directory enumeration position");
const auto position = FileSystem::KernelLseek(fd, 0, 1);
Check(
FileSystem::KernelLseek(fd, 0, 9) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, -1, 0) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, std::numeric_limits<int64_t>::min(), 1) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, std::numeric_limits<int64_t>::max(), 1) ==
Libs::LibKernel::KERNEL_ERROR_EOVERFLOW &&
FileSystem::KernelLseek(fd, 0, 1) == position,
"invalid and overflowing directory seeks preserve the position");
Check(FileSystem::KernelLseek(fd, -19, 2) == end - 19 &&
FileSystem::KernelRead(fd, block.data(), block.size()) == 19 &&
std::memcmp(block.data(), raw.data() + end - 19, 19) == 0,
"raw directory reads support byte positions and stop at EOF");
Check(FileSystem::KernelLseek(fd, 1, 0) == 1 &&
FileSystem::KernelGetdents(fd, block.data(), block.size()) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, 0, 1) == 1,
"directory enumeration rejects an incomplete record position");
Check(FileSystem::KernelLseek(fd, 512, 2) == end + 512 &&
FileSystem::KernelGetdirentries(fd, block.data(), block.size(),
&base) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, 0, 1) == end + 512,
"directory enumeration rejects a position beyond EOF");
Check(FileSystem::KernelRead(
fd, block.data(),
static_cast<size_t>(std::numeric_limits<int>::max()) + 1) ==
Libs::LibKernel::KERNEL_ERROR_EINVAL &&
FileSystem::KernelLseek(fd, 0, 1) == end + 512,
"oversized read fails without changing the directory position");
Check(FileSystem::KernelClose(fd) == OK, "close directory stream");
Check(FileSystem::KernelLseek(fd, 0, 0) ==
Libs::LibKernel::KERNEL_ERROR_EBADF,
"seek rejects a closed descriptor");
FileSystem::Umount("/app0");
}
void CheckAmprOrdering(Loader::SymbolDatabase &symbols, uint32_t file_id) {
Libs::LibAmpr::InitAmpr_1(&symbols);
const auto find = [&](const char *nid) {
const auto *symbol = symbols.FindByNid(nid, Loader::SymbolType::Func);
Check(symbol != nullptr, "AMPR command and submission exports resolve");
return symbol->vaddr;
};
using Unary = void (KYTY_SYSV_ABI *)(void *);
using AprConstructor = void (KYTY_SYSV_ABI *)(void *, void *, void *);
using SetBuffer = int (KYTY_SYSV_ABI *)(void *, void *, uint32_t);
using Offset = uint64_t (KYTY_SYSV_ABI *)(void *);
using WaitAddress = int (KYTY_SYSV_ABI *)(void *, volatile uint64_t *, uint64_t,
uint8_t, uint8_t);
using WriteAddress = int (KYTY_SYSV_ABI *)(void *, volatile uint64_t *, uint64_t);
using ReadFile = int (KYTY_SYSV_ABI *)(void *, uint64_t, uint64_t, uint32_t,
void *, uint64_t, uint64_t);
using WriteKernelEvent = int (KYTY_SYSV_ABI *)(void *, uint64_t, uint64_t, uint64_t,
uint64_t, uint64_t);
struct Result { int32_t result; uint32_t error_offset; };
using SubmitApr = int (KYTY_SYSV_ABI *)(void *, uint32_t, Result *, uint32_t *);
using SubmitAmm = int (KYTY_SYSV_ABI *)(void *, uint32_t, uint32_t, uint32_t *);
using WaitSubmission = int (KYTY_SYSV_ABI *)(uint32_t);
const auto construct = reinterpret_cast<Unary>(find("8aI7R7WaOlc"));
const auto construct_apr = reinterpret_cast<AprConstructor>(find("a8uLzYY--tM"));
const auto construct_amm = reinterpret_cast<Unary>(find("EDq5bqCqYpA"));
const auto destroy = reinterpret_cast<Unary>(find("GuchCTefuZw"));
const auto set_buffer = reinterpret_cast<SetBuffer>(find("N-FSPA4S3nI"));
const auto offset = reinterpret_cast<Offset>(find("GnxKOHEawhk"));
const auto wait_address = reinterpret_cast<WaitAddress>(find("DLfoNxTFNVk"));
const auto write_address = reinterpret_cast<WriteAddress>(find("sJXyWHjP-F8"));
const auto read_file = reinterpret_cast<ReadFile>(find("mQ16-QdKv7k"));
const auto write_event = reinterpret_cast<WriteKernelEvent>(find("H896Pt-yB4I"));
const auto submit_apr = reinterpret_cast<SubmitApr>(find("ASoW5WE-UPo"));
const auto submit_amm = reinterpret_cast<SubmitAmm>(find("NnKhlMJtIsI"));
const auto wait_apr = reinterpret_cast<WaitSubmission>(find("rqwFKI4PAiM"));
const auto wait_amm = reinterpret_cast<WaitSubmission>(find("HXymib4T8gc"));
struct Buffer {
std::array<uint64_t, 5> header {};
std::array<uint32_t, 256> data {};
};
std::array<Buffer, 4> buffers;
const auto reset = [&](size_t apr_count) {
for (size_t i = 0; i < buffers.size(); ++i) {
auto &buffer = buffers[i];
construct(buffer.header.data());
if (i < apr_count) {
construct_apr(buffer.header.data(), &buffer.header[3], &buffer.header[4]);
} else {
construct_amm(buffer.header.data());
}
Check(set_buffer(buffer.header.data(), buffer.data.data(), sizeof(buffer.data)) == OK,
"initialize AMPR command buffer");
}
};
// WaitCompare order: ==, unsigned >/<, !=, wrapped >=, signed >/<.
struct Comparison { uint8_t compare; uint64_t blocked, reference, released; };
constexpr std::array comparisons {
Comparison{0, 1, 2, 2}, Comparison{1, 0x40000000000019c3, 0x40000000000019c3,
0x40000000000019c4},
Comparison{1, 0, INT64_MAX, uint64_t{1} << 63},
Comparison{2, UINT64_MAX, uint64_t{1} << 63, INT64_MAX}, Comparison{3, 2, 2, 3},
Comparison{4, UINT64_MAX - 1, UINT64_MAX, 0},
Comparison{5, UINT64_MAX, 0, 1}, Comparison{6, 0, 0, UINT64_MAX}};
for (const auto &comparison : comparisons) {
reset(3);
uint64_t fence = comparison.blocked;
uint64_t blocked_done = 0, read_done = 0, lower_done = 0;
std::array<char, 3> output {};
std::array<Result, 3> results {{{1234, 5678}, {1234, 5678}, {1234, 5678}}};
std::array<uint32_t, 4> ids {};
auto *blocked = buffers[0].header.data();
auto *reader = buffers[1].header.data();
auto *lower = buffers[2].header.data();
auto *producer = buffers[3].header.data();
Check(wait_address(blocked, &fence, comparison.reference, comparison.compare, 0) == OK &&
write_address(blocked, &blocked_done, 1) == OK &&
read_file(reader, reinterpret_cast<uint64_t>(&buffers[1].header[3]),
reinterpret_cast<uint64_t>(&buffers[1].header[4]), file_id,
output.data(), output.size(), 0) == OK &&
write_address(reader, &read_done, 2) == OK &&
write_address(lower, &lower_done, 3) == OK &&
write_address(producer, &fence, comparison.released) == OK,
"build dependent APR read and later AMM fence producer");
Check(submit_apr(blocked, 3, &results[0], &ids[0]) == OK &&
submit_apr(reader, 3, &results[1], &ids[1]) == OK &&
submit_apr(lower, 4, &results[2], &ids[2]) == OK && wait_apr(ids[2]) == OK,
"APR submit returns while blocked and a lower priority completes");
Check(lower_done == 3 && blocked_done == 0 && read_done == 0 &&
output == std::array<char, 3>{} && results[0].result == 1234 &&
results[1].result == 1234,
"unsatisfied wait blocks later buffers at its priority without publishing completion");
Check(submit_amm(buffers[3].data.data(), static_cast<uint32_t>(offset(producer)), 1,
&ids[3]) == OK && wait_amm(ids[3]) == OK &&
wait_apr(ids[0]) == OK && wait_apr(ids[1]) == OK,
"later AMM submission releases the APR dependency");
Check(blocked_done == 1 && read_done == 2 && std::memcmp(output.data(), "APR", 3) == 0,
"APR reads real file bytes only after its dependency completes");
for (const auto &result : results) {
Check(result.result == OK,
"submission wait observes the completed result");
}
}
reset(1);
namespace EventQueue = Libs::LibKernel::EventQueue;
EventQueue::KernelEqueue queue = EventQueue::KERNEL_EQUEUE_INVALID;
uint64_t ampr_user_data = 1, user_data = 2;
Check(EventQueue::KernelCreateEqueue(&queue, "apr-completion") == OK &&
EventQueue::KernelAddAmprEvent(queue, 42, &r_user_data) == OK &&
EventQueue::KernelAddUserEventEdge(queue, 42) == OK,
"AMPR and user events can share an identifier");
std::array<char, 3> output {};
Result event_result {1234, 5678};
uint32_t event_submission = 0;
auto *reader = buffers[0].header.data();
Check(read_file(reader, reinterpret_cast<uint64_t>(&buffers[0].header[3]),
reinterpret_cast<uint64_t>(&buffers[0].header[4]), file_id,
output.data(), output.size(), 0) == OK &&
write_event(reader, queue, 42, 0x123456789abc, 0, 0) == OK &&
submit_apr(reader, 3, &event_result, &event_submission) == OK &&
wait_apr(event_submission) == OK && event_result.result == OK,
"APR read submits its completion event");
std::array<EventQueue::KernelEvent, 2> events {};
int event_count = 0;
const Libs::LibKernel::KernelUseconds poll = 0;
Check(EventQueue::KernelWaitEqueue(queue, events.data(), 2, &event_count, &poll) == OK &&
event_count == 1 && events[0].ident == 42 && events[0].filter == -25 &&
events[0].data == 0x123456789abc && events[0].udata == &r_user_data &&
std::memcmp(output.data(), "APR", 3) == 0,
"APR completion reports the AMPR filter, payload and registration user data");
Check(EventQueue::KernelDeleteAmprEvent(queue, 42) == OK &&
EventQueue::KernelTriggerEvent(queue, 42, -25, nullptr) ==
Libs::LibKernel::KERNEL_ERROR_ENOENT &&
EventQueue::KernelTriggerUserEvent(queue, 42, &user_data) == OK &&
EventQueue::KernelWaitEqueue(queue, events.data(), 2, &event_count, &poll) == OK &&
event_count == 1 && events[0].filter == EventQueue::KERNEL_EVFILT_USER &&
events[0].udata == &user_data,
"deleting AMPR leaves the user event with the same identifier intact");
Check(EventQueue::KernelDeleteEqueue(queue) == OK, "delete APR completion queue");
reset(0);
uint64_t cpu_fence = 0, amm_done = 0, lower_done = 0;
std::array<uint32_t, 2> ids {};
Check(wait_address(buffers[0].header.data(), &cpu_fence, 0, 1, 0) == OK &&
write_address(buffers[0].header.data(), &amm_done, 1) == OK &&
write_address(buffers[1].header.data(), &lower_done, 1) == OK &&
submit_amm(buffers[0].data.data(), static_cast<uint32_t>(offset(buffers[0].header.data())),
0, &ids[0]) == OK &&
submit_amm(buffers[1].data.data(), static_cast<uint32_t>(offset(buffers[1].header.data())),
1, &ids[1]) == OK && wait_amm(ids[1]) == OK,
"AMM lower priority progresses while its high priority waits");
Check(lower_done == 1 && amm_done == 0, "AMM wait preserves its dependency");
std::atomic_ref(cpu_fence).store(1, std::memory_order_release);
Check(wait_amm(ids[0]) == OK && amm_done == 1,
"AMM observes an external CPU fence store without a submission notification");
for (auto &buffer : buffers) {
destroy(buffer.header.data());
}
}
void CheckAprPaths(const std::filesystem::path &root) {
Loader::SymbolDatabase symbols;
Libs::LibKernelApr::InitLibKernel_1_Apr(&symbols);
const auto *resolve_symbol = symbols.FindByNid("w5fcCG+t31g", Loader::SymbolType::Func);
const auto *each_symbol = symbols.FindByNid("C+Khtbbx2g8", Loader::SymbolType::Func);
Check(resolve_symbol && each_symbol, "APR path exports are registered");
using Resolve = int (KYTY_SYSV_ABI *)(const char *, const char *const *, uint32_t,
uint32_t *, uint64_t *, uint32_t *);
using ResolveEach = int (KYTY_SYSV_ABI *)(const char *, const char *const *, uint32_t,
uint32_t *, uint64_t *, int *);
const auto resolve = reinterpret_cast<Resolve>(resolve_symbol->vaddr);
const auto resolve_each = reinterpret_cast<ResolveEach>(each_symbol->vaddr);
Common::File fixture;
Check(fixture.Create(root / "apr.dat"), "create APR fixture");
fixture.Write("APR", 3);
fixture.Close();
FileSystem::Mount(root, "/app0");
uint32_t expected_id = 0xffffffffu;
for (const auto &parts : {std::array{"", "/app0/apr.dat"},
std::array{"/app0/", "apr.dat"},
std::array{"/", "app0/apr.dat"},
std::array{"/app", "0/apr.dat"}}) {
uint32_t id = 0xffffffffu, error_index = 0xffffffffu;
uint64_t size = 0;
Check(resolve(parts[0], &parts[1], 1, &id, &size, &error_index) == OK &&
id != 0xffffffffu && size == 3,
"APR concatenates empty, one-character and partial-component prefixes");
if (expected_id == 0xffffffffu) {
expected_id = id;
}
Check(id == expected_id, "equivalent APR paths return the same ID");
}
const char *paths[] = {"/app0/missing.dat", "/app0/apr.dat"};
uint32_t ids[2] = {}, error_index = 0xffffffffu;
uint64_t sizes[2] = {1, 1};
int results[2] = {};
Check(resolve_each("", paths, 2, ids, sizes, results) == 1 &&
results[0] == Libs::LibKernel::KERNEL_ERROR_ENOENT && results[1] == OK &&
ids[0] == 0xffffffffu && ids[1] == expected_id && sizes[0] == 0 && sizes[1] == 3,
"APR foreach reports a missing path and continues to the valid file");
// PATH_MAX includes NUL; all components remain below NAME_MAX (255).
std::string longest = "/app0/";
for (int i = 0; i < 3; ++i) {
longest += std::string(254, 'a') + '/';
}
longest += std::string(1023 - longest.size(), 'b');
paths[0] = longest.c_str();
Check(resolve("", paths, 1, ids, sizes, &error_index) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_ENOENT && error_index == 0,
"APR accepts a pathname whose final NUL is at PATH_MAX minus one");
Check(resolve("/", paths, 1, ids, sizes, &error_index) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_ENAMETOOLONG,
"APR rejects concatenated paths exceeding PATH_MAX");
std::array<char, 1024> unterminated;
unterminated.fill('/');
paths[0] = unterminated.data();
Check(resolve("", paths, 1, ids, sizes, &error_index) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_ENAMETOOLONG,
"APR rejects an unterminated pathname");
paths[0] = "apr.dat";
Check(resolve(unterminated.data(), paths, 1, ids, sizes, &error_index) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_ENAMETOOLONG,
"APR rejects an unterminated prefix");
CheckAmprOrdering(symbols, expected_id);
FileSystem::Umount("/app0");
}
std::array<int, 2> CreateTcpPair() {
namespace Net = Libs::Network::Net;
// Guest sockaddr_in: length, family, network-order port/address, padding.
std::array<uint8_t, 16> address {16, 2, 0, 0, 127, 0, 0, 1};
const int listener = Net::Socket(2, 1, 0);
Check(listener >= 0, "create loopback listener");
Check(Net::Bind(listener, address.data(), address.size()) == 0, "bind loopback");
Check(Net::Listen(listener, 1) == 0, "listen on loopback");
uint32_t address_size = address.size();
Check(Net::Getsockname(listener, address.data(), &address_size) == 0,
"get assigned loopback port");
const int writer = Net::Socket(2, 1, 0);
Check(writer >= 0 && Net::Connect(writer, address.data(), address_size) == 0,
"connect wake socket");
const int reader = Net::Accept(listener, nullptr, nullptr);
Check(reader >= 0, "accept wake socket");
Check(Net::SocketClose(listener) == 0, "close listener");
return {reader, writer};
}
#if defined(_WIN32)
void CheckSocketReceiveConcurrency() {
namespace Net = Libs::Network::Net;
const auto [reader, writer] = CreateTcpPair();
const int timeout_ms = 3000;
Check(Net::Setsockopt(reader, 0xffff, 0x1006, &timeout_ms, sizeof(timeout_ms)) == 0,
"bound the blocked receive concurrency fixture");
std::promise<void> entered;
std::promise<int64_t> completed;
auto entered_future = entered.get_future();
auto completed_future = completed.get_future();
std::jthread receiver([&] {
char byte = 0;
entered.set_value();
completed.set_value(Net::Recv(reader, &byte, 1, 0x42));
});
Check(entered_future.wait_for(std::chrono::seconds(2)) == std::future_status::ready,
"start blocked reader");
std::this_thread::sleep_for(std::chrono::milliseconds(50));
char byte = 0;
const auto before_nonblocking = std::chrono::steady_clock::now();
Check(Net::Recv(reader, &byte, 1, 0x80) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_EWOULDBLOCK &&
std::chrono::steady_clock::now() - before_nonblocking < std::chrono::milliseconds(500) &&
completed_future.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout,
"DONTWAIT does not wait behind another blocked reader");
const auto before_close = std::chrono::steady_clock::now();
Check(Net::SocketClose(reader) == 0, "close succeeds while another thread receives");
Check(std::chrono::steady_clock::now() - before_close < std::chrono::seconds(1),
"close does not wait for the blocked receive timeout");
Check(completed_future.wait_for(std::chrono::seconds(1)) == std::future_status::ready,
"close wakes the blocked receive within one second");
Check(completed_future.get() <= 0, "closed receive reports EOF or error");
Check(std::chrono::steady_clock::now() - before_close < std::chrono::seconds(1),
"closing a socket wakes its blocked receive before the receive timeout");
receiver.join();
Check(Net::SocketClose(writer) == 0, "close blocked receive writer");
const auto [shutdown_reader, shutdown_writer] = CreateTcpPair();
Check(Net::Setsockopt(shutdown_reader, 0xffff, 0x1006, &timeout_ms, sizeof(timeout_ms)) == 0 &&
Net::Send(shutdown_writer, "x", 1, 0) == 1 &&
Net::Recv(shutdown_reader, &byte, 1, 0x42) == 1 && byte == 'x' &&
Net::Shutdown(shutdown_reader, 0) == 0 &&
Net::Recv(shutdown_reader, &byte, 1, 0) == -1 &&
*Libs::Posix::GetErrorAddr() == Libs::Posix::POSIX_ESHUTDOWN,
"receive shutdown rejects bytes retained by an earlier peek");
Check(Net::SocketClose(shutdown_reader) == 0 && Net::SocketClose(shutdown_writer) == 0,
"close receive shutdown fixture");
}
void CheckSocketReceiveBuffer(int reader, int writer) {
namespace Net = Libs::Network::Net;
constexpr int PeekWaitAll = 0x42;
constexpr char Payload[] = "abcdef";
const int timeout_ms = 2000;
Check(Net::Setsockopt(reader, 0xffff, 0x1006, &timeout_ms, sizeof(timeout_ms)) == 0,
"bound blocking receive regressions with SO_RCVTIMEO");
Check(Net::Send(writer, Payload, 2, 0) == 2, "send first TCP fragment");
std::jthread sender([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
Check(Net::Send(writer, Payload + 2, 4, 0) == 4, "send second TCP fragment");
});
std::array<char, 8> received {};
Check(Net::Recv(reader, received.data(), 6, PeekWaitAll) == 6 &&
std::memcmp(received.data(), Payload, 6) == 0,
"combined peek waits for fragmented TCP bytes");
sender.join();
received.fill(0);
Check(Net::Recv(reader, received.data(), 6, PeekWaitAll) == 6 &&
std::memcmp(received.data(), Payload, 6) == 0,
"repeated combined peek preserves all bytes");
const int epoll = Net::EpollCreate("buffered receive", 0);
Net::NetEpollEvent registration {};
registration.events = 1;
registration.data.u64 = 0x12345678;
Check(epoll >= 0 && Net::EpollControl(epoll, 1, reader, ®istration) == 0,
"register buffered socket readability");
const auto check_readable = [&](bool expected) {
std::array<uint64_t, 16> readable {};
const auto bit = uint64_t {1} << (reader % 64);
readable[reader / 64] = bit;
const std::array<int64_t, 2> timeout {expected ? 1 : 0, 0};
Check(Net::Select(reader + 1, readable.data(), nullptr, nullptr, timeout.data()) ==
(expected ? 1 : 0) && readable[reader / 64] == (expected ? bit : 0),
"select reflects buffered bytes and their removal");
if (expected) {
auto writable = readable;
Check(Net::Select(reader + 1, readable.data(), writable.data(), nullptr,
timeout.data()) == 2 && readable[reader / 64] == bit &&
writable[reader / 64] == bit,
"select counts readable and writable bits once each");
}
Net::NetEpollEvent event {};