-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathUnitTests.cpp
More file actions
6575 lines (5231 loc) · 273 KB
/
UnitTests.cpp
File metadata and controls
6575 lines (5231 loc) · 273 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
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
UnitTests.cpp
Abstract:
This file contains unit tests for WSL.
--*/
#include "precomp.h"
#include "Common.h"
#include "install.h"
#include <AclAPI.h>
#include <fstream>
#include <filesystem>
#include "wslservice.h"
#include "registry.hpp"
#include "helpers.hpp"
#include "svccomm.hpp"
#include "lxfsshares.h"
#include <userenv.h>
#include <nlohmann/json.hpp>
#include "Distribution.h"
#include "WslCoreConfigInterface.h"
#include "CommandLine.h"
#define LXSST_TEST_USERNAME L"kerneltest"
#define LXSST_LXFS_TEST_DIR L"lxfstest"
#define LXSST_LXFS_MKDIR_COMMAND_LINE \
L"/bin/bash -c \"mkdir /" LXSST_LXFS_TEST_DIR "; chown 1000:1001 /" LXSST_LXFS_TEST_DIR L"\""
#define LXSST_LXFS_CLEANUP_COMMAND_LINE L"/bin/bash -c \"rm -rf /" LXSST_LXFS_TEST_DIR L"\""
#define LXSST_LXFS_TEST_SUB_DIR L"testdir"
#define LXSST_FSTAB_BACKUP_COMMAND_LINE L"/bin/bash -c 'cp /etc/fstab /etc/fstab.bak'"
#define LXSST_FSTAB_SETUP_COMMAND_LINE L"/bin/bash -c 'echo C:\\\\ /mnt/c drvfs metadata 0 0 >> /etc/fstab'"
#define LXSST_FSTAB_CLEANUP_COMMAND_LINE L"/bin/bash -c \"cp /etc/fstab.bak /etc/fstab\""
#define LXSST_TESTS_INSTALL_COMMAND_LINE L"/bin/bash -c 'cd /data/test; ./build_tests.sh'"
#define LXSST_IMPORT_DISTRO_TEST_DIR L"C:\\importtest\\"
#define LXSST_UID_ROOT 0
#define LXSST_GID_ROOT 0
#define LXSST_USERNAME_ROOT L"root"
#define LXSS_OOBE_COMPLETE_NAME L"OOBEComplete"
constexpr auto c_testDistributionEndpoint = L"http://127.0.0.1:12345/";
constexpr auto c_testDistributionJson =
LR"({
\"Distributions\":[
{
\"Name\": \"Debian\",
\"FriendlyName\": \"Debian\",
\"StoreAppId\": \"Dummy\",
\"Amd64\": true,
\"Arm64\": true,
\"Amd64PackageUrl\": null,
\"Arm64PackageUrl\": null,
\"PackageFamilyName\": \"Dummy\"
}
]})";
using wsl::windows::common::wslutil::GetSystemErrorString;
extern std::wstring g_testDistroPath;
namespace UnitTests {
class UnitTests
{
WSL_TEST_CLASS(UnitTests)
TEST_CLASS_SETUP(TestClassSetup)
{
VERIFY_ARE_EQUAL(LxsstuInitialize(FALSE), TRUE);
// Build the unit tests on the Linux side
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(LXSST_TESTS_INSTALL_COMMAND_LINE), (DWORD)0);
return true;
}
TEST_CLASS_CLEANUP(TestClassCleanup)
{
LxsstuLaunchWsl(LXSST_LXFS_CLEANUP_COMMAND_LINE);
LxsstuUninitialize(FALSE);
return true;
}
TEST_METHOD_CLEANUP(MethodCleanup)
{
LxssLogKernelOutput();
return true;
}
// Note: This test should run first since other test cases create files extended attributes, which causes bdstar to emit warnings during export.
TEST_METHOD(ExportDistro)
{
constexpr auto tarPath = L"exported-test-distro.tar";
constexpr auto vhdPath = L"exported-test-distro.vhdx";
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, []() {
LOG_IF_WIN32_BOOL_FALSE(DeleteFile(tarPath));
LOG_IF_WIN32_BOOL_FALSE(DeleteFile(vhdPath));
});
{
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(std::format(L"--export {} {}", LXSS_DISTRO_NAME_TEST_L, tarPath));
VERIFY_ARE_EQUAL(out, L"The operation completed successfully. \r\n");
VERIFY_ARE_EQUAL(err, L"");
}
// Validate that the file is a valid tar
{
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(std::format(L"bash -c 'tar tf {} | grep -iF /root/.bashrc'", tarPath));
VERIFY_ARE_EQUAL(out, L"./root/.bashrc\n");
VERIFY_ARE_EQUAL(err, L"");
}
// Validate that gzip compression works
{
auto [out, err] =
LxsstuLaunchWslAndCaptureOutput(std::format(L"--export {} {} --format tar.gz", LXSS_DISTRO_NAME_TEST_L, tarPath));
VERIFY_ARE_EQUAL(out, L"The operation completed successfully. \r\n");
VERIFY_ARE_EQUAL(err, L"");
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(std::format(L"gzip -t {}", tarPath)), 0L);
}
// Verify that xzip compression works
{
auto [out, err] =
LxsstuLaunchWslAndCaptureOutput(std::format(L"--export {} {} --format tar.xz", LXSS_DISTRO_NAME_TEST_L, tarPath));
VERIFY_ARE_EQUAL(out, L"The operation completed successfully. \r\n");
VERIFY_ARE_EQUAL(err, L"");
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(std::format(L"xz -t {}", tarPath)), 0L);
}
// Validate that exporting as vhd works
if (LxsstuVmMode())
{
WslShutdown(); // TODO: detach disk when distribution is stopped to remove this requirement.
auto [out, err] =
LxsstuLaunchWslAndCaptureOutput(std::format(L"--export {} {} --format vhd", LXSS_DISTRO_NAME_TEST_L, vhdPath));
VERIFY_ARE_EQUAL(out, L"The operation completed successfully. \r\n");
VERIFY_ARE_EQUAL(err, L"");
auto [vhdType, _] = LxsstuLaunchPowershellAndCaptureOutput(std::format(L"(Get-VHD '{}').VhdType", vhdPath));
VERIFY_ARE_EQUAL(vhdType, L"Dynamic\r\n");
}
else
{
auto [out, err] =
LxsstuLaunchWslAndCaptureOutput(std::format(L"--export {} {} --format vhd", LXSS_DISTRO_NAME_TEST_L, vhdPath), -1);
VERIFY_ARE_EQUAL(out, L"This operation is only supported by WSL2.\r\nError code: Wsl/Service/WSL_E_WSL2_NEEDED\r\n");
VERIFY_ARE_EQUAL(err, L"");
}
}
WSL2_TEST_METHOD(SystemdSafeMode)
{
SKIP_TEST_UNSTABLE(); // TODO: Re-enable when this issue is solved in main.
auto revert = EnableSystemd();
// generate a new test config with safe mode enabled
WslConfigChange config(LxssGenerateTestConfig({.safeMode = true}));
// verify that even though systemd is enabled, safe mode prevents it from executing
VERIFY_IS_FALSE(IsSystemdRunning(L"--system", 1));
config.Update(L"");
// disable safe mode and verify that it systemd runs
VERIFY_IS_TRUE(IsSystemdRunning(L"--system"));
}
WSL2_TEST_METHOD(SystemdDisabled)
{
// tests that systemd does not run without the wsl.conf option enabled
// run and check the output of systemctl --system
VERIFY_IS_FALSE(IsSystemdRunning(L"--system", 1));
}
WSL2_TEST_METHOD(SystemdSystem)
{
auto cleanup = wil::scope_exit([] {
// clean up wsl.conf file
const std::wstring disableSystemdCmd(LXSST_REMOVE_DISTRO_CONF_COMMAND_LINE);
LxsstuLaunchWsl(disableSystemdCmd);
TerminateDistribution();
});
auto revert = EnableSystemd();
VERIFY_IS_TRUE(IsSystemdRunning(L"--system"));
// Validate that systemd-networkd-wait-online.service is masked.
auto [out, _] =
LxsstuLaunchWslAndCaptureOutput(L"systemctl status systemd-networkd-wait-online.service | grep -iF Loaded:");
VERIFY_ARE_EQUAL(out, L" Loaded: masked (Reason: Unit systemd-networkd-wait-online.service is masked.)\n");
// Validate that NetworkManager-wait-online.service is masked.
auto [outNm, __] =
LxsstuLaunchWslAndCaptureOutput(L"systemctl status NetworkManager-wait-online.service | grep -iF Loaded:");
VERIFY_ARE_EQUAL(outNm, L" Loaded: masked (Reason: Unit NetworkManager-wait-online.service is masked.)\n");
}
WSL2_TEST_METHOD(SystemdUser)
{
// enable systemd before creating the user.
// if not called first, the runtime directories needed for --user will not have been created
auto cleanup = EnableSystemd();
// create test user and run test as that user
ULONG TestUid;
ULONG TestGid;
CreateUser(LXSST_TEST_USERNAME, &TestUid, &TestGid);
auto userCleanup = wil::scope_exit([]() { LxsstuLaunchWsl(L"userdel " LXSST_TEST_USERNAME); });
auto validateUserSession = [&]() {
// verify that the user service is running
const std::wstring isServiceActiveCmd =
std::format(L"-u {} systemctl is-active user@{}.service ; exit 0", LXSST_TEST_USERNAME, TestUid);
std::wstring out;
std::wstring err;
try
{
std::tie(out, err) = LxsstuLaunchWslAndCaptureOutput(isServiceActiveCmd.data());
}
CATCH_LOG();
Trim(out);
if (out.compare(L"active") != 0)
{
LogError(
"Unexpected output from systemd: %ls. Stderr: %ls, cmd: %ls", out.c_str(), err.c_str(), isServiceActiveCmd.c_str());
VERIFY_FAIL();
}
// Verify that /run/user/<uid> is a writable tmpfs mount visible in both mount namespaces.
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"touch /run/user/" + std::to_wstring(TestUid) + L"/dummy-test-file"), 0u);
auto command = L"mount | grep -iF 'tmpfs on /run/user/" + std::to_wstring(TestUid) + L" type tmpfs (rw'";
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(command), 0u);
const auto nonElevatedToken = GetNonElevatedToken();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(command, nullptr, nullptr, nullptr, nonElevatedToken.get()), 0u);
};
// Validate user sessions state with gui apps disabled.
WslConfigChange config(LxssGenerateTestConfig({.guiApplications = false}));
{
validateUserSession();
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(std::format(L"--user {} echo $DISPLAY", LXSST_TEST_USERNAME));
VERIFY_ARE_EQUAL(out, L"\n");
// N.B. The XDG_RUNTIME_DIR variable is always set by init even if gui apps are disabled.
std::tie(out, err) = LxsstuLaunchWslAndCaptureOutput(std::format(L"--user {} echo $XDG_RUNTIME_DIR", LXSST_TEST_USERNAME));
VERIFY_ARE_EQUAL(out, std::format(L"/run/user/{}\n", TestUid));
}
// Validate user sessions state with gui apps enabled.
{
config.Update(LxssGenerateTestConfig({.guiApplications = true}));
validateUserSession();
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(std::format(L"--user {} echo $DISPLAY", LXSST_TEST_USERNAME));
VERIFY_ARE_EQUAL(out, L":0\n");
std::tie(out, err) = LxsstuLaunchWslAndCaptureOutput(std::format(L"--user {} echo $XDG_RUNTIME_DIR", LXSST_TEST_USERNAME));
VERIFY_ARE_EQUAL(out, std::format(L"/run/user/{}\n", TestUid));
}
// Create a 'broken' /run/user and validate that the warning is correctly displayed.
{
TerminateDistribution();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"chmod 000 /run/user"), 0L);
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(std::format(L"-u {} echo OK", LXSST_TEST_USERNAME));
VERIFY_ARE_EQUAL(out, L"OK\n");
VERIFY_ARE_EQUAL(
err, L"wsl: Failed to start the systemd user session for 'kerneltest'. See journalctl for more details.\n");
}
}
static bool IsSystemdRunning(const std::wstring& SystemdScope, int ExpectedExitCode = 0)
{
// run and check the output of systemctl --system
const auto systemctlCmd = std::format(L"systemctl '{}' is-system-running ; exit 0", SystemdScope);
std::wstring out;
std::wstring error;
// capture the output of systemctl and trim for good measure
try
{
std::tie(out, error) = LxsstuLaunchWslAndCaptureOutput(systemctlCmd.c_str(), ExpectedExitCode);
}
CATCH_LOG()
Trim(out);
// ensure that systemd is either running in a degraded or running state
if ((out.compare(L"degraded") == 0) || (out.compare(L"running") == 0))
{
return true;
}
LogInfo(
"Error when checking if systemd is running: %ls (scope: %ls, stderr: %ls)", out.c_str(), SystemdScope.c_str(), error.c_str());
return false;
}
WSL2_TEST_METHOD(SystemdNoClearTmpUnit)
{
// ensures that we don't leave state on exit
auto cleanup = EnableSystemd("initTimeout=0");
// Wait for systemd to be started
VERIFY_NO_THROW(wsl::shared::retry::RetryWithTimeout<void>(
[&]() { THROW_HR_IF(E_UNEXPECTED, !IsSystemdRunning(L"--system")); }, std::chrono::seconds(1), std::chrono::minutes(1)));
// Validate that the X11 socket has not been deleted
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"test -d /tmp/.X11-unix"), 0L);
}
WSL2_TEST_METHOD(SystemdBinfmtIsRestored)
{
// Override WSL's binfmt interpreter
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"mkdir -p /usr/lib/binfmt.d && echo ':WSLInterop:M::MZ::/bin/echo:PF' > /usr/lib/binfmt.d/dummy.conf"), 0L);
auto cleanupBinfmt = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, []() {
LxsstuLaunchWsl(L"rm /usr/lib/binfmt.d/dummy.conf");
WslShutdown(); // Required since this test registers a custom binfmt interpreter.
});
{
// Enable systemd (restarts distro).
auto cleanupSystemd = EnableSystemd();
auto validateBinfmt = []() {
// Validate that WSL's binfmt interpreter is still in place.
auto [cmdOutput, _] = LxsstuLaunchWslAndCaptureOutput(L"cmd.exe /c echo ok");
VERIFY_ARE_EQUAL(cmdOutput, L"ok\r\n");
};
validateBinfmt();
// Validate that this still works after restarting the distribution.
TerminateDistribution();
validateBinfmt();
// Validate that stopping or restarting systemd-binfmt doesn't break interop.
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"systemctl stop systemd-binfmt.service"), 0u);
validateBinfmt();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"systemctl restart systemd-binfmt.service"), 0u);
validateBinfmt();
// Validate that the unit is regenerated after a daemon-reload.
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"systemctl daemon-reload && systemctl restart systemd-binfmt.service"), 0u);
validateBinfmt();
}
{
// Enable systemd (restarts distro).
auto cleanupSystemd = EnableSystemd("protectBinfmt=false");
// Validate that WSL's binfmt interpreter is overridden
auto [output, _] = LxsstuLaunchWslAndCaptureOutput(L"cmd.exe /c echo ok");
VERIFY_IS_TRUE(wsl::shared::string::IsEqual(output, L"/mnt/c/Windows/system32/cmd.exe cmd.exe /c echo ok\n", true));
}
}
TEST_METHOD(Dup)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests dup", L"Dup"));
}
WSL1_TEST_METHOD(Epoll)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests epoll", L"Epoll"));
}
TEST_METHOD(EventFd)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests eventfd", L"EventFd"));
}
TEST_METHOD(Flock)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests flock", L"Flock"));
}
WSL1_TEST_METHOD(Fork)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests fork", L"Fork"));
}
WSL1_TEST_METHOD(FsCommonLxFs)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests fscommon", L"fscommon_lxfs"));
}
TEST_METHOD(GetSetId)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests get_set_id", L"get_set_id"));
}
WSL1_TEST_METHOD(Inotify)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests inotify", L"INOTIFY"));
}
#if !defined(_ARM64_)
TEST_METHOD(ResourceLimits)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests resourcelimits", L"resourcelimits"));
}
TEST_METHOD(Select)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests select", L"Select"));
}
#endif
TEST_METHOD(Madvise)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests madvise", L"madvise"));
}
TEST_METHOD(Mprotect)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests mprotect", L"mprotect"));
}
WSL1_TEST_METHOD(Pipe)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests pipe", L"Pipe"));
}
WSL1_TEST_METHOD(Sched)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests sched", L"sched"));
}
WSL1_TEST_METHOD(SocketNonblocking)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests socket_nonblock", L"socket_nonblocking"));
}
WSL1_TEST_METHOD(Splice)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests splice", L"Splice"));
}
WSL1_TEST_METHOD(Sysfs)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests sysfs", L"SysFs"));
}
WSL1_TEST_METHOD(Tty)
{
auto OriginalHandles = UseOriginalStdHandles();
auto Restore = wil::scope_exit([&OriginalHandles]() { RestoreTestStdHandles(OriginalHandles); });
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests tty", L"tty"));
}
WSL1_TEST_METHOD(Utimensat)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests utimensat", L"Utimensat"));
}
TEST_METHOD(WaitPid)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests waitpid", L"WaitPid"));
}
TEST_METHOD(Brk)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests brk", L"brk"));
}
TEST_METHOD(Mremap)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests mremap", L"mremap"));
}
TEST_METHOD(VfsAccess)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests vfsaccess", L"vfsaccess"));
}
WSL1_TEST_METHOD(DevPt)
{
auto OriginalHandles = UseOriginalStdHandles();
auto Restore = wil::scope_exit([&OriginalHandles]() { RestoreTestStdHandles(OriginalHandles); });
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests dev_pt", L"dev_pt"));
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests dev_pt_2", L"dev_pt_2"));
}
WSL1_TEST_METHOD(Timer)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests timer", L"timer"));
}
WSL1_TEST_METHOD(SysInfo)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests sysinfo", L"Sysinfo"));
}
TEST_METHOD(TimerFd)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests timerfd", L"timerfd"));
}
WSL1_TEST_METHOD(Ioprio)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests ioprio", L"Ioprio"));
}
TEST_METHOD(Interop)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests interop", L"interop"));
//
// Run wsl.exe with a very long command line. This ensures that the buffer
// resizing logic that is used by the WSL init daemon is able to correctly
// handle very long messages.
//
// N.B. /bin/true ignores all arguments and always returns 0.
//
std::wstring Command{L"/bin/true "};
Command += std::wstring(0x1000, L'x');
VERIFY_IS_TRUE(LxsstuLaunchWsl(Command.c_str()) == 0);
// Validate that windows executable can run from the linux filesystem. See: https://github.com/microsoft/WSL/issues/10812
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"cp /mnt/c/Program\\ Files/WSL/wsl.exe /tmp"), 0L);
auto [out, _] =
LxsstuLaunchWslAndCaptureOutput(L"WSLENV=WSL_UTF8 WSL_UTF8=1 WSL_INTEROP=/run/WSL/1_interop /tmp/wsl.exe --version");
VERIFY_IS_TRUE(out.find(TEXT(WSL_PACKAGE_VERSION)) != std::string::npos);
}
static std::wstring FormUserCommandLine(_In_ const std::wstring& Username, _In_ ULONG Uid, _In_ ULONG Gid)
{
return std::format(L"/data/test/wsl_unit_tests user {} {} {}", Username, Uid, Gid);
}
TEST_METHOD(User)
{
//
// Create a test user and run the test as that user.
//
ULONG TestUid;
ULONG TestGid;
CreateUser(LXSST_TEST_USERNAME, &TestUid, &TestGid);
std::wstring CommandLine = FormUserCommandLine(LXSST_TEST_USERNAME, TestUid, TestGid);
LogInfo("Running test as user %s", LXSST_TEST_USERNAME);
VERIFY_NO_THROW(LxsstuRunTest(CommandLine.c_str(), L"user", LXSST_TEST_USERNAME));
//
// Add the user to 64 more groups to make sure > 32 groups is supported.
//
{
DistroFileChange groups(L"/etc/group", true);
CommandLine = std::format(L"-- for i in $(seq 1 64); do groupadd group$i; usermod -a -G group$i {}; done", LXSST_TEST_USERNAME);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(CommandLine), (DWORD)0);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(std::format(L"{} {} {}", WSL_USER_ARG_LONG, LXSST_TEST_USERNAME, "echo success")), (DWORD)0);
}
//
// Run the test as root.
//
ULONG RootUid;
ULONG RootGid;
CreateUser(LXSST_USERNAME_ROOT, &RootUid, &RootGid);
CommandLine = FormUserCommandLine(LXSST_USERNAME_ROOT, LXSST_UID_ROOT, LXSST_GID_ROOT);
LogInfo("Running test as user %s", LXSST_USERNAME_ROOT);
VERIFY_NO_THROW(LxsstuRunTest(CommandLine.c_str(), L"user", LXSST_USERNAME_ROOT));
//
// Set the default user to the newly created user.
//
// N.B. Modifying the default UID should cause the instance to be recreated and the plan9 server launched as the default user.
//
const auto wslSupport =
wil::CoCreateInstance<LxssUserSession, IWslSupport>(CLSCTX_LOCAL_SERVER | CLSCTX_ENABLE_CLOAKING | CLSCTX_ENABLE_AAA);
ULONG Version;
ULONG DefaultUid;
wil::unique_cotaskmem_array_ptr<wil::unique_cotaskmem_ansistring> DefaultEnvironment{};
ULONG WslFlags;
VERIFY_SUCCEEDED(wslSupport->GetDistributionConfiguration(
LXSS_DISTRO_NAME_TEST_L, &Version, &DefaultUid, DefaultEnvironment.size_address<ULONG>(), &DefaultEnvironment, &WslFlags));
VERIFY_SUCCEEDED(wslSupport->SetDistributionConfiguration(LXSS_DISTRO_NAME_TEST_L, TestUid, WslFlags));
auto cleanup = wil::scope_exit([&] {
try
{
VERIFY_SUCCEEDED(wslSupport->SetDistributionConfiguration(LXSS_DISTRO_NAME_TEST_L, DefaultUid, WslFlags));
}
catch (...)
{
LogError("Error while restoring default user");
}
});
//
// Create a new file using the 9p server.
//
const std::wstring Path = L"\\\\wsl.localhost\\" LXSS_DISTRO_NAME_TEST_L L"\\data\\test\\default_user_test";
const wil::unique_hfile File(CreateFile(
Path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL));
if (!File)
{
LogError("Failed to create file, error=%lu", GetLastError());
VERIFY_FAIL();
}
//
// Ensure the new file was created with the correct uid.
//
VERIFY_ARE_EQUAL(
LxsstuLaunchWsl(L"stat -c %U /data/test/default_user_test | grep -iF kerneltest", nullptr, nullptr, nullptr, nullptr), 0u);
}
WSL1_TEST_METHOD(Execve)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests execve", L"Execve"));
}
TEST_METHOD(Xattr)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests xattr", L"xattr"));
}
WSL1_TEST_METHOD(Namespace)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests namespace", L"Namespace"));
}
TEST_METHOD(BinFmt)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests binfmt", L"BinFmt"));
//
// Perform a shutdown since the binfmt test modifies the binfmt config.
//
WslShutdown();
}
TEST_METHOD(Cgroup)
{
//
// For WSL1, run the cgroup unit test. For WSL2, ensure the cgroupv2 filesystem is mounted in the expected location.
//
if (!LxsstuVmMode())
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests cgroup", L"cgroup"));
}
else
{
VERIFY_ARE_EQUAL(
LxsstuLaunchWsl(
L"mount | grep -iF 'cgroup2 on /sys/fs/cgroup type cgroup2 (rw,nosuid,nodev,noexec,relatime,nsdelegate)'", nullptr, nullptr, nullptr, nullptr),
0u);
}
}
WSL1_TEST_METHOD(Netlink)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests netlink", L"Netlink"));
}
WSL1_TEST_METHOD(Random)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests random", L"random"));
}
TEST_METHOD(Keymgmt)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests keymgmt", L"Keymgmt"));
}
WSL1_TEST_METHOD(Shm)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests shm", L"shm"));
}
WSL1_TEST_METHOD(Sem)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests sem", L"sem"));
}
WSL1_TEST_METHOD(Ttys)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests ttys", L"Ttys"));
}
WSL1_TEST_METHOD(OverlayFs)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests overlayfs", L"OverlayFs"));
}
TEST_METHOD(Auxv)
{
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests auxv", L"auxv"));
}
TEST_METHOD(WslInfo)
{
if (LxsstuVmMode())
{
// Ensure the `-n` option to not print newline works by validating newline counts.
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode | wc -l | grep 1"), 0u);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode -n | wc -l | grep 0"), 0u);
// Ensure various wslinfo functionally works as expected.
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode | grep -iF 'nat'"), 0u);
WslConfigChange config(LxssGenerateTestConfig({.networkingMode = wsl::core::NetworkingMode::None}));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode | grep -iF 'none'"), 0u);
if (AreExperimentalNetworkingFeaturesSupported() && IsHyperVFirewallSupported())
{
config.Update(LxssGenerateTestConfig({.networkingMode = wsl::core::NetworkingMode::Mirrored}));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode | grep -iF 'mirrored'"), 0u);
}
for (const auto enabled : {true, false})
{
config.Update(LxssGenerateTestConfig({.guiApplications = enabled}));
#ifdef WSL_DEV_INSTALL_PATH
VERIFY_ARE_EQUAL(
LxsstuLaunchWsl(std::format(L"wslinfo --msal-proxy-path | grep -iF $(wslpath '{}')", TEXT(WSL_DEV_INSTALL_PATH))), 0u);
#else
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --msal-proxy-path | grep -iF '/mnt/c/Program Files/WSL/msal.wsl.proxy.exe'"), 0u);
#endif
}
}
else
{
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"wslinfo --networking-mode | grep -iF 'wsl1'"), 0u);
}
{
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(L"wslinfo --version");
VERIFY_ARE_EQUAL(out, std::format(L"{}\n", WSL_PACKAGE_VERSION));
VERIFY_ARE_EQUAL(err, L"");
}
{
// Ensure the old version query command still works.
const auto [out, err] = LxsstuLaunchWslAndCaptureOutput(L"wslinfo --wsl-version");
VERIFY_ARE_EQUAL(out, std::format(L"{}\n", WSL_PACKAGE_VERSION));
VERIFY_ARE_EQUAL(err, L"");
}
{
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(L"wslinfo --invalid", 1);
VERIFY_ARE_EQUAL(out, L"");
VERIFY_ARE_EQUAL(
err,
L"Invalid command line argument: --invalid\nPlease use 'wslinfo --help' to get a list of supported "
L"arguments.\n");
}
{
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(L"wslinfo --vm-id -n");
VERIFY_ARE_EQUAL(err, L"");
if (LxsstuVmMode())
{
// Ensure that the response from wslinfo has the VM ID.
auto guid = wsl::shared::string::ToGuid(out);
VERIFY_IS_TRUE(guid.has_value());
VERIFY_IS_FALSE(IsEqualGUID(guid.value(), GUID_NULL));
// Validate that the VM ID is not propagated to user commands.
std::tie(out, err) = LxsstuLaunchWslAndCaptureOutput(L"echo -n \"$WSL2_VM_ID\"");
VERIFY_ARE_EQUAL(out, L"");
VERIFY_ARE_EQUAL(err, L"");
}
else
{
VERIFY_ARE_EQUAL(out, L"wsl1");
}
}
}
TEST_METHOD(FsTab)
{
//
// Revert the fstab file and restart the instance so everything is back in
// the default state after this test.
//
auto cleanup = wil::scope_exit([&] {
try
{
LxsstuLaunchWsl(LXSST_FSTAB_CLEANUP_COMMAND_LINE);
TerminateDistribution();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"/bin/true"), 0u);
}
catch (...)
{
LogError("Error while cleaning up the fstab");
}
});
//
// Create an entry in the /etc/fstab file to explicitly mount C:.
//
VERIFY_ARE_EQUAL(0u, LxsstuLaunchWsl(LXSST_FSTAB_BACKUP_COMMAND_LINE));
VERIFY_ARE_EQUAL(0u, LxsstuLaunchWsl(LXSST_FSTAB_SETUP_COMMAND_LINE));
TerminateDistribution();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"/bin/true"), 0u);
//
// The test will make sure /mnt/c is mounted with the options specified in
// /etc/fstab, and that it's mounted only once.
//
VERIFY_NO_THROW(LxsstuRunTest(L"/data/test/wsl_unit_tests fstab", L"fstab"));
}
TEST_METHOD(X11SocketOverTmpMount)
{
if (!LxsstuVmMode())
{
return;
}
auto cleanup = wil::scope_exit([&] {
try
{
LxsstuLaunchWsl(LXSST_FSTAB_CLEANUP_COMMAND_LINE);
TerminateDistribution();
}
catch (...)
{
LogError("Error while cleaning up the fstab");
}
});
WslConfigChange configChange(LxssGenerateTestConfig({.guiApplications = true}));
//
// Create an entry in the /etc/fstab file to add a tmpfs over /tmp.
//
VERIFY_ARE_EQUAL(0u, LxsstuLaunchWsl(LXSST_FSTAB_BACKUP_COMMAND_LINE));
VERIFY_ARE_EQUAL(0u, LxsstuLaunchWsl(L"echo 'tmpfs /tmp tmpfs rw,nodev,nosuid,size=50M 0 0' > /etc/fstab"));
TerminateDistribution();
auto ValidateBindMount = [](HANDLE Token) {
//
// Validate that the bind mount is present.
//
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L" mount | grep -iF 'none on /tmp/.X11-unix type tmpfs'", nullptr, nullptr, nullptr, Token), 0u);
};
//
// Verify that /tmp is mounted in both namespaces.
//
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"mount | grep -iF 'tmpfs on /tmp type tmpfs'", nullptr, nullptr, nullptr, nullptr), 0u);
const auto nonElevatedToken = GetNonElevatedToken();
VERIFY_ARE_EQUAL(
LxsstuLaunchWsl(L"mount | grep -iF 'tmpfs on /tmp type tmpfs'", nullptr, nullptr, nullptr, nonElevatedToken.get()), 0u);
//
// Validate that the X11 bind mount is present and valid in both namespaces.
//
ValidateBindMount(nullptr);
ValidateBindMount(nonElevatedToken.get());
}
TEST_METHOD(ImportDistro)
{
const auto tarFileName = LXSST_IMPORT_DISTRO_TEST_DIR L"test.tar";
const auto rootfsDirectoryName = LXSST_IMPORT_DISTRO_TEST_DIR L"rootfs";
const auto vhdFileName = LXSST_IMPORT_DISTRO_TEST_DIR L"ext4.vhdx";
auto cleanup = wil::scope_exit([&] {
try
{
VERIFY_IS_TRUE(DeleteFileW(tarFileName));
VERIFY_IS_TRUE(RemoveDirectoryW(rootfsDirectoryName));
VERIFY_IS_TRUE(DeleteFileW(vhdFileName));
VERIFY_IS_TRUE(RemoveDirectoryW(LXSST_IMPORT_DISTRO_TEST_DIR));
}
catch (...)
{
LogError("Error during cleanup")
}
});
//
// Create a dummy tar file, rootfs folder, and vhdx. These will be used
// to ensure that the user cannot import a distribution over an existing one
// even if distro registration registry keys are not present.
//
VERIFY_IS_TRUE(CreateDirectoryW(LXSST_IMPORT_DISTRO_TEST_DIR, NULL));
VERIFY_IS_TRUE(CreateDirectoryW(rootfsDirectoryName, NULL));
{
const wil::unique_hfile tarFile{CreateFileW(
tarFileName, GENERIC_WRITE, (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)};
VERIFY_IS_FALSE(!tarFile);
const wil::unique_hfile vhdFile{CreateFileW(
vhdFileName, GENERIC_WRITE, (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)};
VERIFY_IS_FALSE(!vhdFile);
}
auto validateOutput = [](LPCWSTR commandLine, const std::wstring& expectedOutput, DWORD expectedExitCode = -1) {
auto [out, err] = LxsstuLaunchWslAndCaptureOutput(commandLine, expectedExitCode);
VERIFY_ARE_EQUAL(expectedOutput, out);
VERIFY_ARE_EQUAL(L"", err);
};
auto version = LxsstuVmMode() ? 2 : 1;
auto commandLine = std::format(L"--import dummy {} {} --version {}", LXSST_IMPORT_DISTRO_TEST_DIR, tarFileName, version);
if (LxsstuVmMode())
{
validateOutput(
commandLine.c_str(),
std::format(
L"Failed to create disk '{}ext4.vhdx': The file exists. \r\n"
L"Error code: Wsl/Service/RegisterDistro/ERROR_FILE_EXISTS\r\n",
LXSST_IMPORT_DISTRO_TEST_DIR));
}
else
{
validateOutput(
commandLine.c_str(),
L"The file exists. \r\n"
L"Error code: Wsl/Service/RegisterDistro/ERROR_FILE_EXISTS\r\n");
}
commandLine = std::format(L"--import dummy {} {} --version {}", LXSST_IMPORT_DISTRO_TEST_DIR, vhdFileName, version);
validateOutput(commandLine.c_str(), L"This looks like a VHD file. Use --vhd to import a VHD instead of a tar.\r\n");
if (!LxsstuVmMode())
{
commandLine = std::format(L"--import dummy {} {} --vhd --version 1", LXSST_IMPORT_DISTRO_TEST_DIR, vhdFileName);
validateOutput(
commandLine.c_str(),
L"This operation is only supported by WSL2.\r\n"
L"Error code: Wsl/Service/RegisterDistro/WSL_E_WSL2_NEEDED\r\n");
}
//