-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathMountTests.cpp
More file actions
1486 lines (1137 loc) · 52.4 KB
/
MountTests.cpp
File metadata and controls
1486 lines (1137 loc) · 52.4 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:
MountTests.cpp
Abstract:
This file contains test cases for the disk mounting logic.
--*/
#include "precomp.h"
#include "Common.h"
#define TEST_MOUNT_DISK L"TestDisk.vhd"
#define TEST_MOUNT_VHD L"TestVhd.vhd"
#define TEST_UNMOUNT_VHD_DNE L"TestVhdNotHere.vhd"
#define TEST_MOUNT_NAME L"testmount"
#define SKIP_UNSUPPORTED_ARM64_MOUNT_TEST() \
if constexpr (wsl::shared::Arm64) \
{ \
WSL_TEST_VERSION_REQUIRED(27653); \
}
namespace MountTests {
// Disks sometimes take a bit of time to become available when attached back to the host.
constexpr auto c_diskOpenTimeoutMs = 120000;
class SetAutoMountPolicy
{
public:
SetAutoMountPolicy() = delete;
SetAutoMountPolicy(const SetAutoMountPolicy&) = delete;
SetAutoMountPolicy& operator=(const SetAutoMountPolicy&) = delete;
SetAutoMountPolicy(SetAutoMountPolicy&& Other) = default;
SetAutoMountPolicy& operator=(SetAutoMountPolicy&&) = default;
SetAutoMountPolicy(bool Enable) : PreviousState(GetAutoMountState())
{
if (Enable != PreviousState)
{
SetAutoMountState(Enable);
}
else
{
PreviousState.reset();
}
}
~SetAutoMountPolicy()
{
if (PreviousState.has_value())
{
SetAutoMountState(PreviousState.value());
}
}
private:
static bool GetAutoMountStateFromOutput(const std::wstring& Output)
{
if (Output.find(L"Automatic mounting of new volumes enabled") != std::wstring::npos)
{
return true;
}
else if (Output.find(L"Automatic mounting of new volumes disabled") != std::wstring::npos)
{
return false;
}
LogError("Unexpected diskpart output: '%s'", Output.c_str());
VERIFY_FAIL(L"Failed to parse diskpart's output");
return false;
}
static bool GetAutoMountState()
{
std::wstring cmd = L"diskpart.exe";
return GetAutoMountStateFromOutput(LxsstuLaunchCommandAndCaptureOutput(cmd.data(), "automount\r\n").first);
}
static void SetAutoMountState(bool Enabled)
{
LogInfo("Setting automount policy to %i", Enabled);
std::wstring cmd = L"diskpart.exe";
const auto input = std::string("automount ") + (Enabled ? "enable\r\n" : "disable\r\n");
auto [output, _] = LxsstuLaunchCommandAndCaptureOutput(cmd.data(), input.c_str());
VERIFY_ARE_EQUAL(Enabled, GetAutoMountStateFromOutput(output));
}
std::optional<bool> PreviousState;
};
class MountTests
{
std::wstring DiskDevice;
std::wstring VhdDevice;
wil::unique_tokeninfo_ptr<TOKEN_USER> User = wil::get_token_information<TOKEN_USER>();
std::unique_ptr<wsl::windows::common::security::privilege_context> PrivilegeState;
DWORD DiskNumber = 0;
SetAutoMountPolicy AutoMountPolicy{false};
struct ExpectedMountState
{
size_t PartitionIndex;
std::optional<std::wstring> Type;
std::optional<std::wstring> Options;
};
struct ExpectedDiskState
{
std::wstring Path;
std::vector<ExpectedMountState> Mounts;
};
WSL_TEST_CLASS(MountTests)
TEST_CLASS_SETUP(TestClassSetup)
{
VERIFY_ARE_EQUAL(LxsstuInitialize(false), TRUE);
if (!LxsstuVmMode())
{
return true;
}
// Needed to open processes under te
PrivilegeState = wsl::windows::common::security::AcquirePrivilege(SE_DEBUG_NAME);
// Create a 20MB vhd for testing mounting passthrough disks
DeleteFileW(TEST_MOUNT_DISK);
try
{
LxsstuLaunchPowershellAndCaptureOutput(L"New-Vhd -Path " TEST_MOUNT_DISK " -SizeBytes 20MB");
}
CATCH_LOG()
// Mount it in Windows
auto [output, _] = LxsstuLaunchPowershellAndCaptureOutput(L"(Mount-VHD " TEST_MOUNT_DISK " -PassThru | Get-Disk).Number");
Trim(output);
DiskNumber = std::stoul(output);
// Construct the disk path
DiskDevice = L"\\\\.\\PhysicalDrive" + output;
LogInfo("Mounted the passthrough test vhd as %ls", DiskDevice.c_str());
// Create a 20MB vhd for testing mount --vhd
DeleteFileW(TEST_MOUNT_VHD);
LxsstuLaunchPowershellAndCaptureOutput(L"New-Vhd -Path " TEST_MOUNT_VHD " -SizeBytes 20MB");
VhdDevice = wsl::windows::common::filesystem::GetFullPath(TEST_MOUNT_VHD);
LogInfo("Create mount --vhd test vhd as %ls", VhdDevice.c_str());
return true;
}
// Uninitialize the tests.
TEST_CLASS_CLEANUP(TestClassCleanup)
{
if (LxsstuVmMode())
{
PrivilegeState.reset();
LxsstuLaunchWsl(L"--unmount");
WaitForDiskReady();
try
{
LxsstuLaunchPowershellAndCaptureOutput(L"Dismount-Vhd -Path " TEST_MOUNT_DISK);
}
CATCH_LOG()
DeleteFileW(TEST_MOUNT_DISK);
DeleteFileW(TEST_MOUNT_VHD);
}
VERIFY_NO_THROW(LxsstuUninitialize(false));
return true;
}
TEST_METHOD_CLEANUP(MethodCleanup)
{
if (!LxsstuVmMode())
{
return true;
}
LxssLogKernelOutput();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount"), (DWORD)0);
WaitForDiskReady();
return true;
}
// Attach a vhd, but don't mount it
WSL2_TEST_METHOD(TestBareMountVhd)
{
TestBareMountImpl(true);
}
// Mount one partition using --vhd and validate that options are correctly applied
WSL2_TEST_METHOD(TestMountOnePartitionVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountOnePartitionImpl(true);
}
// Mount two partitions using --vhd on the same disk
WSL2_TEST_METHOD(TestMountTwoPartitionsVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountTwoPartitionsImpl(true);
}
// Run a bare mount using --vhd and then mount a partition
WSL2_TEST_METHOD(TestAttachThenMountVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestAttachThenMountImpl(true);
}
// Mount the disk directly
WSL2_TEST_METHOD(TestMountWholeDiskVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountWholeDiskImpl(true);
}
// Test that mount state is deleted on shutdown (--vhd)
WSL2_TEST_METHOD(TestMountStateIsDeletedOnShutdownVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountStateIsDeletedOnShutdownImpl(true);
}
WSL2_TEST_METHOD(TestFilesystemDetectionWholeDisk)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestFilesystemDetectionWholeDiskImpl(false);
}
WSL2_TEST_METHOD(TestFilesystemDetectionWholeDiskVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestFilesystemDetectionWholeDiskImpl(true);
}
WSL2_TEST_METHOD(TestMountTwoPartitionsWithDetection)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountTwoPartitionsWithDetectionImpl(false);
}
WSL2_TEST_METHOD(TestMountTwoPartitionsWithDetectionVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountTwoPartitionsWithDetectionImpl(true);
}
WSL2_TEST_METHOD(TestFilesystemDetectionFail)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestFilesystemDetectionFailImpl(false);
}
WSL2_TEST_METHOD(TestFilesystemDetectionFailVhd)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestFilesystemDetectionFailImpl(true);
}
// Test specifying a mount name for a vhd
WSL2_TEST_METHOD(SpecifyMountName)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
const auto mountCommand = L"--mount " + VhdDevice + L" --vhd --name " + TEST_MOUNT_NAME;
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition
FormatDisk({L"ext4"}, true);
// Mount it
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(mountCommand + L" --partition 1"), (DWORD)0);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
const std::wstring diskName(TEST_MOUNT_NAME);
auto mountTarget = L"/mnt/wsl/" + diskName;
ValidateMountPoint(disk + L"1", mountTarget);
ValidateDiskState({VhdDevice, {{1, {}, {}}}}, keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + VhdDevice), (DWORD)0);
WaitForDiskReady();
// Validate that the mount folder was deleted
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"test -e " + mountTarget), (DWORD)1);
// Mount the same partition, but with a specific mount option
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(mountCommand + L" --partition 1 --options \"data=ordered\""), (DWORD)0);
// Validate that the mount option was properly passed
disk = GetBlockDeviceInWsl();
ValidateMountPoint(disk + L"1", mountTarget, L"data=ordered");
ValidateDiskState({VhdDevice, {{1, {}, L"data=ordered"}}}, keepAlive);
// Let the VM timeout
WaitForVmTimeout(keepAlive);
// Validate that the disk is re-mounted in the same place
disk = GetBlockDeviceInWsl();
ValidateMountPoint(disk + L"1", mountTarget);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + VhdDevice), (DWORD)0);
WaitForDiskReady();
}
// Test ensuring that name collision detection works in --mount --name
WSL2_TEST_METHOD(SpecifyMountNameCollision)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
const auto mountCommand = L"--mount " + VhdDevice + L" --vhd --name " + TEST_MOUNT_NAME;
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition and one fat partitions
FormatDisk({L"ext4", L"vfat"}, true);
// Attempt to mount both partitions with the same mount name; partition 2 should fail
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(mountCommand + L" --partition 1"), (DWORD)0);
VERIFY_ARE_NOT_EQUAL(LxsstuLaunchWsl(mountCommand + L" --partition 2 --type vfat"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount first mount did succeed
const std::wstring diskName(TEST_MOUNT_NAME);
ValidateMountPoint(disk + L"1", L"/mnt/wsl/" + diskName, {}, L"ext4");
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + VhdDevice), (DWORD)0);
WaitForDiskReady();
}
// Test that multiple partitions can be mounted with --name
WSL2_TEST_METHOD(SpecifyMountNameTwoPartitions)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
const auto mountCommandOne = L"--mount " + VhdDevice + L" --vhd --name " + TEST_MOUNT_NAME + L"p1";
const auto mountCommandTwo = L"--mount " + VhdDevice + L" --vhd --name " + TEST_MOUNT_NAME + L"p2";
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition and one fat partitions
FormatDisk({L"ext4", L"vfat"}, true);
// Attempt to mount both partitions with the same mount name; partition 2 should fail
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(mountCommandOne + L" --partition 1"), (DWORD)0);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(mountCommandTwo + L" --partition 2 --type vfat"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount first mount did succeed
const std::wstring diskName(TEST_MOUNT_NAME);
ValidateMountPoint(disk + L"1", L"/mnt/wsl/" + diskName + L"p1", {}, L"ext4");
ValidateMountPoint(disk + L"2", L"/mnt/wsl/" + diskName + L"p2", {}, L"vfat");
ValidateDiskState({VhdDevice, {{1, {}, {}}, {2, {L"vfat"}, {}}}}, keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + VhdDevice), (DWORD)0);
WaitForDiskReady();
}
// Test relative mount/unmounting of a --vhd
WSL2_TEST_METHOD(RelativePathUnmount)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " TEST_MOUNT_VHD L" --vhd --bare"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " TEST_MOUNT_VHD), (DWORD)0);
}
// Test relative mount/unmounting of a --vhd that does not exist
WSL2_TEST_METHOD(RelativePathUnmountNoFileExists)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " TEST_MOUNT_VHD L" --vhd --bare"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Try unmounting a VHD not created and verify that it was not successful
VERIFY_ARE_NOT_EQUAL(LxsstuLaunchWsl(L"--unmount " TEST_UNMOUNT_VHD_DNE), (DWORD)0);
}
WSL2_TEST_METHOD(AbsolutePathVhdUnmount)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " TEST_MOUNT_VHD L" --vhd --bare"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
const auto absolutePath = std::filesystem::absolute(TEST_MOUNT_VHD);
// Validate that the vhd path doesn't start with '\\?'
VERIFY_IS_FALSE(absolutePath.wstring().starts_with(L"\\"));
// Validate the unmounting by absolute path is successful
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + absolutePath.wstring()), (DWORD)0);
}
WSL2_TEST_METHOD(AbsolutePathVhdUnmountAfterVMTimeout)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " TEST_MOUNT_VHD L" --vhd --bare"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
WaitForVmTimeout(keepAlive);
const auto absolutePath = std::filesystem::absolute(TEST_MOUNT_VHD);
// Validate that the vhd path doesn't start with '\\?'
VERIFY_IS_FALSE(absolutePath.wstring().starts_with(L"\\"));
// Validate the unmounting by absolute path is successful
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + absolutePath.wstring()), (DWORD)0);
}
// Attach a disk, but don't mount it
WSL2_TEST_METHOD(TestBareMount)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestBareMountImpl(false);
}
// Validate that attached disks that were offline when attached
// are still offline when detached
WSL2_TEST_METHOD(TestOfflineDiskStaysOffline)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
auto diskHandle = wsl::windows::common::disk::OpenDevice(DiskDevice.c_str(), GENERIC_ALL, c_diskOpenTimeoutMs);
wsl::windows::common::disk::SetOnline(diskHandle.get(), false);
diskHandle.reset();
ValidateOffline(true);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --bare"), (DWORD)0);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
ValidateDiskState({DiskDevice, {}}, keepAlive);
disk = GetBlockDeviceInWsl();
VERIFY_IS_FALSE(GetBlockDeviceMount(disk).has_value());
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
ValidateOffline(true);
diskHandle = wsl::windows::common::disk::OpenDevice(DiskDevice.c_str(), GENERIC_ALL, c_diskOpenTimeoutMs);
wsl::windows::common::disk::SetOnline(diskHandle.get(), true);
diskHandle.reset();
ValidateOffline(false);
}
// Mount one partition and validate that options are correctly applied
WSL2_TEST_METHOD(TestMountOnePartition)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountOnePartitionImpl(false);
}
// Mount two partitions on the same disk
WSL2_TEST_METHOD(TestMountTwoPartitions)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountTwoPartitionsImpl(false);
}
// Mount a fat partition
WSL2_TEST_METHOD(TestMountFatPartition)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ntfs partition
FormatDisk({L"vfat"}, false);
// Mount it
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1" + L" --type vfat"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
auto mountTarget = L"/mnt/wsl/" + trimmedDiskName + L"p1";
ValidateMountPoint(disk + L"1", mountTarget, {}, L"vfat");
ValidateDiskState({DiskDevice, {{1, {L"vfat"}, {}}}}, keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
WaitForDiskReady();
ValidateOffline(false);
}
// Mount the disk directly
WSL2_TEST_METHOD(TestMountWholeDisk)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountWholeDiskImpl(false);
}
WSL2_TEST_METHOD(TestMountStateIsDeletedOnShutdown)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestMountStateIsDeletedOnShutdownImpl(false);
}
// Validate that a failure to mount a disk isn't fatal
WSL2_TEST_METHOD(TestMountFailuresArentFatal)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition
FormatDisk({L"ext4"}, false);
// Mount it
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1 --type ext4"), (DWORD)0);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
ValidateDiskState({DiskDevice, {{1, {L"ext4"}, {}}}}, keepAlive);
// Check that the disk is still mounted properly (ValidateDiskState restarts the VM)
disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
ValidateMountPoint(disk + L"1", L"/mnt/wsl/" + trimmedDiskName + L"p1", {}, L"ext4");
// Wait for vm timeout
WaitForVmTimeout(keepAlive);
// Voluntarily set a wrong filesystem in the saved state
auto key = wsl::windows::common::registry::OpenOrCreateLxssDiskMountsKey(User->User.Sid);
auto subKeys = wsl::windows::common::registry::EnumKeys(key.get(), KEY_ALL_ACCESS);
VERIFY_ARE_EQUAL(subKeys.size(), 1);
wsl::windows::common::registry::WriteString(subKeys.begin()->second.get(), L"1", L"Type", L"badfs");
keepAlive.Set();
// The disk should be present
disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// But not mounted
ValidateMountPoint(disk + L"1", {});
// Now put a bad disk path, so that the disk fails to attach
WaitForVmTimeout(keepAlive);
key = wsl::windows::common::registry::OpenOrCreateLxssDiskMountsKey(User->User.Sid);
subKeys = wsl::windows::common::registry::EnumKeys(key.get(), KEY_ALL_ACCESS);
VERIFY_ARE_EQUAL(subKeys.size(), 1);
wsl::windows::common::registry::WriteString(subKeys.begin()->second.get(), nullptr, L"Disk", L"BadDisk");
keepAlive.Reset();
// Restart the service
RestartWslService();
// Run a dummy command to trigger a VM start
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"echo foo"), (DWORD)0);
// The disk should still be online, because it failed to attach
ValidateOffline(false);
}
// wsl --unmount should succeed even when no disk is mounted
WSL2_TEST_METHOD(UnmountWithoutAnyDisk)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount"), (DWORD)0);
}
// Mount two partitions on the same disk and validate that the mount is restored
WSL2_TEST_METHOD(TestMountTwoPartitionsAfterTimeout)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition and one fat partitions
FormatDisk({L"ext4", L"vfat"}, false);
// Mount then both
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1"), (DWORD)0);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 2 --type vfat"), (DWORD)0);
ValidateDiskState({DiskDevice, {{1, {}, {}}, {2, {L"vfat"}, {}}}}, keepAlive);
// Validate that our disk is still mounted
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
ValidateMountPoint(disk + L"1", L"/mnt/wsl/" + trimmedDiskName + L"p1", {}, L"ext4");
ValidateMountPoint(disk + L"2", L"/mnt/wsl/" + trimmedDiskName + L"p2", {}, L"vfat");
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
}
// Validate that non-admin can remount saved disks
WSL2_TEST_METHOD(TestMount1PartitionAndRemountAsNonAdmin)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
FormatDisk({L"ext4"}, false);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1"), (DWORD)0);
ValidateDiskState({DiskDevice, {{1, {}, {}}}}, keepAlive);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Let the UVM timeout
WaitForVmTimeout(keepAlive);
// Restart wsl as a non-elevated user
const auto nonElevatedToken = GetNonElevatedToken();
// Launch wsl non-elevated
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"echo dummy", nullptr, nullptr, nullptr, nonElevatedToken.get()), (DWORD)0);
keepAlive.Set();
// Validate that our disk is still attached
disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
ValidateMountPoint(disk + L"1", L"/mnt/wsl/" + trimmedDiskName + L"p1", {}, L"ext4");
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
}
// Run a bare mount and then mount a partition
WSL2_TEST_METHOD(TestAttachThenMount)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
TestAttachThenMountImpl(false);
}
// Validate that unmounting works when the UVM is not running
WSL2_TEST_METHOD(TestMountOnePartitionAfterTimeout)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition
FormatDisk({L"ext4"}, false);
// Mount it
ValidateOffline(false);
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1"), (DWORD)0);
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
ValidateOffline(true);
// Wait for vm timeout
WaitForVmTimeout(keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
// The UVM shouldn't be running
VERIFY_IS_FALSE(GetVmmempPid().has_value());
// No state should be left in registry
const auto key = wsl::windows::common::registry::OpenOrCreateLxssDiskMountsKey(User->User.Sid);
VERIFY_ARE_EQUAL(wsl::windows::common::registry::EnumKeys(key.get(), KEY_READ).size(), 0);
}
// Validate that the proper mount error is returned if the filesystem type is wrong
WSL2_TEST_METHOD(TestMountPartitionWithWrongFs)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition
FormatDisk({L"ext4"}, false);
// Mount it
wsl::windows::common::SvcComm service;
VERIFY_ARE_EQUAL(service.AttachDisk(DiskDevice.c_str(), LXSS_ATTACH_MOUNT_FLAGS_PASS_THROUGH), S_OK);
const auto result = service.MountDisk(DiskDevice.c_str(), LXSS_ATTACH_MOUNT_FLAGS_PASS_THROUGH, 1, nullptr, L"vfat", nullptr);
VERIFY_ARE_EQUAL(result.Result, -22); //-EINVAL
VERIFY_ARE_EQUAL(result.Step, 3); // LxMiniInitMountStepMount
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
}
// Validate that the proper mount error is returned if the partition can't be found
WSL2_TEST_METHOD(TestMountPartitionWithBadPartitionIndex)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 fat partition
FormatDisk({L"vfat"}, false);
// Try to mount a partition that doesn't exist
wsl::windows::common::SvcComm service;
VERIFY_ARE_EQUAL(service.AttachDisk(DiskDevice.c_str(), LXSS_ATTACH_MOUNT_FLAGS_PASS_THROUGH), S_OK);
const auto result = service.MountDisk(DiskDevice.c_str(), LXSS_ATTACH_MOUNT_FLAGS_PASS_THROUGH, 2, nullptr, L"vfat", nullptr);
VERIFY_ARE_EQUAL(result.Result, -2); // -ENOENT
VERIFY_ARE_EQUAL(result.Step, 2); // LxMiniInitMountStepFindPartition
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
}
// Validate that disk aren't detached if in use by other processes
WSL2_TEST_METHOD(TestDeviceCantBeMountedIfInUse)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
{
// Format-Volume fails without automount enabled
SetAutoMountPolicy AutoMountPolicy{true};
// Reset the disk
LxsstuLaunchPowershellAndCaptureOutput(L"Clear-Disk -confirm:$false -RemoveData -Number " + std::to_wstring(DiskNumber));
LxsstuLaunchPowershellAndCaptureOutput(L"Initialize-Disk -confirm:$false -Number " + std::to_wstring(DiskNumber));
// Create one fat partition
LxsstuLaunchPowershellAndCaptureOutput(
L"New-Partition -DiskNumber " + std::to_wstring(DiskNumber) +
L" -UseMaximumSize \
| Format-Volume -FileSystem FAT");
}
// Mount it in Windows
auto [letter, _] = LxsstuLaunchPowershellAndCaptureOutput(
L"Set-Partition -DiskNumber " + std::to_wstring(DiskNumber) + L" -PartitionNumber 1" + L" -NewDriveLetter Y");
// Open a file under that partition
wil::unique_handle file(CreateFile(L"Y:\\foo.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr));
const char* fileContent = "LOW!";
THROW_LAST_ERROR_IF(!WriteFile(file.get(), fileContent, static_cast<DWORD>(strlen(fileContent)), nullptr, nullptr));
// Validate that the disk can't be mounted (TODO: Find a way to validate the failure reason)
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1 --type vfat"), (DWORD)-1);
// Close the file and mount it
file.reset();
WaitForDiskReady();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1 --type vfat"), (DWORD)0);
// Validate that the file content is correct
const auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
ValidateMountPoint(disk + L"1", {L"/mnt/wsl/" + trimmedDiskName + L"p1"}, {}, L"vfat");
auto [output, __] = LxsstuLaunchWslAndCaptureOutput(L"cat /mnt/wsl/" + trimmedDiskName + L"p1/foo.txt");
VERIFY_ARE_EQUAL(output, wsl::shared::string::MultiByteToWide(fileContent));
}
WSL2_TEST_METHOD(TestMountWithFlagOption)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
WslKeepAlive keepAlive;
// Create a MBR disk with 1 ext4 partition
FormatDisk({L"ext4"}, false);
// Mount it
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1 --options sync"), (DWORD)0);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
// Validate that the mount succeeded
std::wstring trimmedDiskName(DiskDevice);
Trim(trimmedDiskName);
auto mountTarget = L"/mnt/wsl/" + trimmedDiskName + L"p1";
ValidateMountPoint(disk + L"1", mountTarget, L"sync");
ValidateDiskState({DiskDevice, {{1, {}, L"sync"}}}, keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
WaitForDiskReady();
// Mount the same partition, but with both a flag and a non-flag option
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount " + DiskDevice + L" --partition 1 --options data=ordered,sync"), (DWORD)0);
// Validate that the mount option was properly passed
disk = GetBlockDeviceInWsl();
ValidateMountPoint(disk + L"1", mountTarget, L"ync,relatime,data=ordered");
// Note: relatime is set by default
ValidateDiskState({DiskDevice, {{1, {}, L"data=ordered,sync"}}}, keepAlive);
// Unmount the disk
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount " + DiskDevice), (DWORD)0);
WaitForDiskReady();
}
WSL1_TEST_METHOD(TestAttachFailsWithoutWsl2Distro)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
// Attempt to mount a disk with only a WSL1 distro
wsl::windows::common::SvcComm service;
VERIFY_ARE_EQUAL(service.AttachDisk(L"Dummy", LXSS_ATTACH_MOUNT_FLAGS_PASS_THROUGH), WSL_E_WSL2_NEEDED);
}
WSL2_TEST_METHOD(VhdWithSpaces)
{
SKIP_UNSUPPORTED_ARM64_MOUNT_TEST();
LxsstuLaunchPowershellAndCaptureOutput(L"New-Vhd -Path 'vhd with spaces.vhdx' -SizeBytes 20MB");
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, []() {
WslShutdown();
if (!DeleteFile(L"vhd with spaces.vhdx"))
{
LogInfo("Failed to delete vhd, %i", GetLastError());
};
});
WslKeepAlive keepAlive;
// Validate that relative path mounting and unmounting works
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount \"vhd with spaces.vhdx\" --bare --vhd"), (DWORD)0);
auto disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount \"vhd with spaces.vhdx\""), (DWORD)0);
// Validate that absolute path mounting and unmounting works
const std::wstring fullPath = wsl::windows::common::filesystem::GetFullPath(L"vhd with spaces.vhdx");
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--mount \"" + fullPath + L"\" --bare --vhd"), (DWORD)0);
disk = GetBlockDeviceInWsl();
VERIFY_IS_TRUE(IsBlockDevicePresent(disk));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"--unmount \"" + fullPath + L"\""), (DWORD)0);
}
void WaitForDiskReady() const
{
const auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(30);
while (timeout > std::chrono::steady_clock::now())
{
try
{
auto disk = wsl::windows::common::disk::OpenDevice(DiskDevice.c_str(), GENERIC_READ, c_diskOpenTimeoutMs);
wsl::windows::common::disk::ValidateDiskVolumesAreReady(disk.get());
return;
}
catch (...)
{
auto error = std::system_category().message(wil::ResultFromCaughtException());
LogInfo("Caught '%S' while waiting for disk", error.c_str());
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
}
VERIFY_FAIL(L"Timeout waiting for disk");
}
void ValidateOffline(bool offline) const
{
const auto disk = wsl::windows::common::disk::OpenDevice(DiskDevice.c_str(), FILE_READ_ATTRIBUTES, c_diskOpenTimeoutMs);
VERIFY_ARE_EQUAL(!offline, wsl::windows::common::disk::IsDiskOnline(disk.get()));
}
static std::wstring GetBlockDeviceInWsl()
{
// Wait for the disk to be attached
const auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(30);
bool done = false;
while (true)
{
for (wchar_t name = 'a'; name < 'z'; name++)
{
std::wstring cmd = L"-u root blockdev --getsize64 /dev/sd";
cmd += name;
std::wstring out;
try
{
out = LxsstuLaunchWslAndCaptureOutput(cmd.data()).first;
}
CATCH_LOG()
Trim(out);
// Disk size is 20MB, so 20 * 1024 * 1024 bytes
if (out == L"20971520")
{
return std::wstring(L"/dev/sd") + name;
}
}
if (done)
{
break;
}
done = std::chrono::steady_clock::now() > timeout;
}
VERIFY_FAIL(L"Failed to find the block device in WSL");
// Unreachable.
return {};
}
static bool IsBlockDevicePresent(const std::wstring& Device)
{
const auto Cmd = L"test -e " + Device;
return LxsstuLaunchWsl(Cmd.data()) == 0;
}
static std::optional<std::vector<std::wstring>> GetBlockDeviceMount(const std::wstring& device)
{
const std::wstring cmd(L"cat /proc/mounts");
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(cmd.data());
LogInfo("/proc/mounts content: '%ls'", out.c_str());
std::wistringstream output(out);
std::wstring line;
while (std::getline(output, line))
{
if (wcsstr(line.data(), device.data()) == line.data())
{