-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathWslCoreVm.cpp
More file actions
2846 lines (2399 loc) · 111 KB
/
WslCoreVm.cpp
File metadata and controls
2846 lines (2399 loc) · 111 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:
WslCoreVm.cpp
Abstract:
This file contains utility VM function definitions.
--*/
#include "precomp.h"
#include "WslCoreVm.h"
#include "WslCoreNetworkingSupport.h"
#include <lxfsshares.h>
#include "disk.hpp"
#include "WslCoreInstance.h"
#include "NatNetworking.h"
#include "BridgedNetworking.h"
#include "MirroredNetworking.h"
#include "WslCoreFirewallSupport.h"
#include "DnsResolver.h"
#include "VirtioNetworking.h"
#include <TraceLoggingProvider.h>
using msl::utilities::SafeInt;
using wsl::windows::common::helpers::WindowsBuildNumbers;
using namespace wsl::windows::common::registry;
using namespace wsl::windows::common::string;
using namespace std::string_literals;
// The default high-gap MMIO space is 16GB
#define DEFAULT_HIGH_MMIO_GAP_IN_MB (16 * _1KB)
// Start of unaddressable memory if guest only supports the minimum 36-bit addressing.
#define MAX_36_BIT_PAGE_IN_MB (0x1000000000 / _1MB)
#define WSLG_SHARED_MEMORY_SIZE_MB 8192
#define PAGE_SIZE 0x1000
static constexpr size_t c_bootEntropy = 0x1000;
static constexpr auto c_localDevicesKey = L"SOFTWARE\\Microsoft\\Terminal Server Client\\LocalDevices";
#define LXSS_ENABLE_GUI_APPS() (m_vmConfig.EnableGuiApps && (m_systemDistroDeviceId != ULONG_MAX))
using namespace wsl::windows::common;
using wsl::core::NetworkingMode;
using wsl::core::networking::NetworkEndpoint;
using wsl::core::networking::NetworkSettings;
using wsl::shared::Localization;
using wsl::windows::common::Context;
using wsl::windows::common::ExecutionContext;
namespace {
INT64
RequiredExtraMmioSpaceForPmemFileInMb(_In_ PCWSTR FilePath)
{
// Open the file and retrieve the file's size.
const wil::unique_hfile fileHandle{CreateFile(FilePath, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr)};
THROW_LAST_ERROR_IF(!fileHandle);
LARGE_INTEGER fileSizeBytes;
THROW_IF_WIN32_BOOL_FALSE(GetFileSizeEx(fileHandle.get(), &fileSizeBytes));
// The file is mapped to the VM using PCI BARs, which can only be a power of two. Therefore,
// round the file size up to the nearest power of two.
fileSizeBytes.QuadPart = wsl::windows::common::helpers::RoundUpToNearestPowerOfTwo(fileSizeBytes.QuadPart);
// Convert from bytes to megabytes. Ensure that we don't truncate a 512kb file to 0mb.
return std::max(fileSizeBytes.QuadPart / static_cast<INT64>(_1MB), 1i64);
}
} // namespace
WslCoreVm::WslCoreVm(_In_ wsl::core::Config&& VmConfig) :
m_vmConfig(std::move(VmConfig)), m_traceClient(m_vmConfig.EnableTelemetry)
{
}
std::unique_ptr<WslCoreVm> WslCoreVm::Create(_In_ const wil::shared_handle& UserToken, _In_ wsl::core::Config&& VmConfig, _In_ const GUID& VmId)
{
auto newInstance = std::unique_ptr<WslCoreVm>{new WslCoreVm{std::move(VmConfig)}};
try
{
const auto startTimeMs = GetTickCount64();
auto privateKernel = !newInstance->m_vmConfig.KernelPath.empty();
// Log telemetry on how long it took to create the VM
WSL_LOG_TELEMETRY(
"CreateVmBegin", PDT_ProductAndServicePerformance, TraceLoggingValue(VmId, "vmId"), CONFIG_TELEMETRY(newInstance->m_vmConfig));
newInstance->Initialize(VmId, UserToken);
const auto timeToCreateVmMs = GetTickCount64() - startTimeMs;
WSL_LOG_TELEMETRY(
"CreateVmEnd",
PDT_ProductAndServicePerformance,
TraceLoggingValue(privateKernel, "privateKernel"),
TraceLoggingValue(newInstance->m_kernelVersionString.c_str(), "kernelVersion"),
TraceLoggingValue(newInstance->m_runtimeId, "vmId"),
TraceLoggingValue(timeToCreateVmMs, "timeToCreateVmMs"),
CONFIG_TELEMETRY(newInstance->m_vmConfig));
}
catch (...)
{
const auto hr = wil::ResultFromCaughtException();
// Log telemetry when the WSL VM fails to start including the error
WSL_LOG_TELEMETRY(
"FailedToStartVm",
PDT_ProductAndServicePerformance,
TraceLoggingValue(VmId, "vmId"),
TraceLoggingValue(hr, "error"),
CONFIG_TELEMETRY(newInstance->m_vmConfig));
if (hr == HRESULT_FROM_WIN32(WSAENOTCONN) || hr == HRESULT_FROM_WIN32(WSAECONNRESET) || hr == HRESULT_FROM_WIN32(WSAETIMEDOUT))
{
// A kernel panic can cause an hvsocket error. If we hit this, wait one second for an HCS notification to give a better error for the user.
if (newInstance->m_vmCrashEvent.wait(1000))
{
if (newInstance->m_vmCrashLogFile.has_value())
{
THROW_HR_WITH_USER_ERROR(
WSL_E_VM_CRASHED,
wsl::shared::Localization::MessageWSL2Crashed() + L"\r\n" +
Localization::MessageWSL2CrashedStackTrace(newInstance->m_vmCrashLogFile.value()));
}
else
{
THROW_HR_WITH_USER_ERROR(WSL_E_VM_CRASHED, wsl::shared::Localization::MessageWSL2Crashed());
}
}
}
throw;
}
return newInstance;
}
void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken)
{
auto signalEarlyTermination = wil::scope_exit([&] { m_terminatingEvent.SetEvent(); });
// create a restricted version of the token.
m_userToken = UserToken;
m_restrictedToken = wsl::windows::common::security::CreateRestrictedToken(m_userToken.get());
// Make a copy of the user sid.
auto tokenUser = wil::get_token_information<TOKEN_USER>(m_userToken.get());
THROW_IF_WIN32_BOOL_FALSE(::CopySid(sizeof(m_userSid), &m_userSid.Sid, tokenUser->User.Sid));
// Generate a machine ID string based on the VM ID. This is used for some HCS APIs.
m_machineId = wsl::shared::string::GuidToString<wchar_t>(VmId, wsl::shared::string::GuidToStringFlags::Uppercase);
// Set the install path of the package.
m_installPath = wsl::windows::common::wslutil::GetBasePath();
// Initialize the path to the tools folder which also serves as the default rootfs path.
m_rootFsPath = m_installPath / LXSS_TOOLS_DIRECTORY;
// Store the path of the user profile.
m_userProfile = wsl::windows::common::helpers::GetUserProfilePath(m_userToken.get());
// Query the Windows version.
m_windowsVersion = wsl::windows::common::helpers::GetWindowsVersion();
// Create a temporary folder for the VM.
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
m_tempPath = wsl::windows::common::filesystem::GetTempFolderPath(m_userToken.get()) / m_machineId;
wil::CreateDirectoryDeep(m_tempPath.c_str());
m_tempDirectoryCreated = true;
}
CATCH_LOG();
// If a private kernel was not specified, use the default.
m_defaultKernel = m_vmConfig.KernelPath.empty();
if (m_defaultKernel)
{
#ifdef WSL_KERNEL_PATH
m_vmConfig.KernelPath = TEXT(WSL_KERNEL_PATH);
#else
m_vmConfig.KernelPath = m_rootFsPath / LXSS_VM_MODE_KERNEL_NAME;
#endif
}
else
{
if (!wsl::windows::common::filesystem::FileExists(m_vmConfig.KernelPath.c_str()))
{
THROW_HR_WITH_USER_ERROR(
WSL_E_CUSTOM_KERNEL_NOT_FOUND,
Localization::MessageCustomKernelNotFound(
wsl::windows::common::helpers::GetWslConfigPath(m_userToken.get()), m_vmConfig.KernelPath.c_str()));
}
// Direct boot is not supported on ARM64. Modify the rootfs directory to be a temporary directory that contains
// copies of the initrd file and private kernel.
if constexpr (wsl::shared::Arm64)
{
auto impersonate = wil::impersonate_token(m_userToken.get());
m_rootFsPath = m_tempPath / LXSS_ROOTFS_DIRECTORY;
wil::CreateDirectoryDeep(m_rootFsPath.c_str());
auto initRdPath = m_installPath / LXSS_TOOLS_DIRECTORY / LXSS_VM_MODE_INITRD_NAME;
auto targetPath = m_rootFsPath / LXSS_VM_MODE_INITRD_NAME;
THROW_IF_WIN32_BOOL_FALSE(CopyFileW(initRdPath.c_str(), targetPath.c_str(), TRUE));
targetPath = m_rootFsPath / LXSS_VM_MODE_KERNEL_NAME;
THROW_IF_WIN32_BOOL_FALSE(CopyFileW(m_vmConfig.KernelPath.c_str(), targetPath.c_str(), TRUE));
}
}
// If the user did not specify custom modules, use the default modules only if using the default kernel.
if (m_vmConfig.KernelModulesPath.empty())
{
if (m_defaultKernel)
{
#ifdef WSL_KERNEL_MODULES_PATH
m_vmConfig.KernelModulesPath = std::wstring(TEXT(WSL_KERNEL_MODULES_PATH));
#else
m_vmConfig.KernelModulesPath = m_rootFsPath / L"modules.vhd";
#endif
}
}
else
{
if (!wsl::windows::common::filesystem::FileExists(m_vmConfig.KernelModulesPath.c_str()))
{
THROW_HR_WITH_USER_ERROR(
WSL_E_CUSTOM_KERNEL_NOT_FOUND,
Localization::MessageCustomKernelModulesNotFound(
wsl::windows::common::helpers::GetWslConfigPath(m_userToken.get()), m_vmConfig.KernelModulesPath.c_str()));
}
if (m_defaultKernel)
{
THROW_HR_WITH_USER_ERROR(WSL_E_CUSTOM_KERNEL_NOT_FOUND, Localization::MessageMismatchedKernelModulesError());
}
}
// If debug console was requested, create a randomly-named pipe and spawn a wslhost process to read from the pipe.
//
// N.B. wslhost.exe is launched at medium integrity level and its lifetime
// is tied to the lifetime of the utility VM.
if (m_vmConfig.EnableDebugConsole || !m_vmConfig.DebugConsoleLogFile.empty())
{
try
{
m_vmConfig.EnableDebugConsole = true;
m_comPipe0 = wsl::windows::common::helpers::GetUniquePipeName();
}
CATCH_LOG()
}
// If the system supports virtio console serial ports, use dmesg capture for telemetry and/or debug output.
// Legacy serial is much slower, so this is not enabled without virtio console support.
auto enableVirtioSerial = m_vmConfig.EnableVirtio && helpers::IsVirtioSerialConsoleSupported();
m_vmConfig.EnableDebugShell &= enableVirtioSerial;
if (enableVirtioSerial)
{
try
{
bool enableTelemetry = TraceLoggingProviderEnabled(g_hTraceLoggingProvider, WINEVENT_LEVEL_INFO, 0);
m_dmesgCollector = DmesgCollector::Create(
VmId, m_vmExitEvent, enableTelemetry, m_vmConfig.EnableDebugConsole, m_comPipe0, m_vmConfig.EnableEarlyBootLogging, {});
WSL_LOG("DMESG collector created");
if (m_vmConfig.EnableDebugShell)
{
m_debugShellPipe = wsl::windows::common::wslutil::GetDebugShellPipeName(&m_userSid.Sid);
}
// Initialize the guest telemetry logger.
m_gnsTelemetryLogger = GuestTelemetryLogger::Create(VmId, m_vmExitEvent);
}
CATCH_LOG()
}
if (m_vmConfig.EnableDebugConsole)
{
try
{
// If specified, create a file to log the debug console output.
wil::unique_hfile logFile;
if (!m_vmConfig.DebugConsoleLogFile.empty())
{
auto impersonate = wil::impersonate_token(m_userToken.get());
logFile.reset(CreateFileW(
m_vmConfig.DebugConsoleLogFile.c_str(), FILE_APPEND_DATA, (FILE_SHARE_READ | FILE_SHARE_WRITE), nullptr, OPEN_ALWAYS, 0, nullptr));
LOG_LAST_ERROR_IF(!logFile);
}
wsl::windows::common::helpers::LaunchDebugConsole(
m_comPipe0.c_str(), !!m_dmesgCollector, m_restrictedToken.get(), logFile ? logFile.get() : nullptr, !m_vmConfig.EnableTelemetry);
}
CATCH_LOG()
}
// Create the utility VM and store the runtime ID.
std::wstring json = GenerateConfigJson();
m_system = wsl::windows::common::hcs::CreateComputeSystem(m_machineId.c_str(), json.c_str());
m_runtimeId = wsl::windows::common::hcs::GetRuntimeId(m_system.get());
WI_ASSERT(IsEqualGUID(VmId, m_runtimeId));
// Initialize the guest device manager.
m_guestDeviceManager = std::make_shared<GuestDeviceManager>(m_machineId, m_runtimeId);
// Create a socket listening for connections from mini_init.
m_listenSocket = wsl::windows::common::hvsocket::Listen(m_runtimeId, LX_INIT_UTILITY_VM_INIT_PORT);
if (m_vmConfig.MaxCrashDumpCount >= 0)
{
auto crashDumpSocket = wsl::windows::common::hvsocket::Listen(m_runtimeId, LX_INIT_UTILITY_VM_CRASH_DUMP_PORT);
THROW_LAST_ERROR_IF(!crashDumpSocket);
m_crashDumpCollectionThread =
std::thread{[this, socket = std::move(crashDumpSocket)]() mutable { CollectCrashDumps(std::move(socket)); }};
}
// Register a callback to detect if the utility VM exits unexpectedly.
wsl::windows::common::hcs::RegisterCallback(m_system.get(), s_OnExit, this);
signalEarlyTermination.release();
// Start the utility VM.
try
{
wsl::windows::common::hcs::StartComputeSystem(m_system.get(), json.c_str());
}
catch (...)
{
// Reset m_system so we don't try to wait for termination in the destructor, since the VM isn't even running.
m_system.reset();
throw;
}
// Add GPUs to the utility VM.
if (m_vmConfig.EnableGpuSupport)
{
ExecutionContext context(Context::ConfigureGpu);
hcs::ModifySettingRequest<hcs::GpuConfiguration> gpuRequest{};
gpuRequest.ResourcePath = L"VirtualMachine/ComputeTopology/Gpu";
gpuRequest.RequestType = hcs::ModifyRequestType::Update;
gpuRequest.Settings.AssignmentMode = hcs::GpuAssignmentMode::Mirror;
gpuRequest.Settings.AllowVendorExtension = true;
if (wsl::windows::common::hcs::IsDisableVgpuSettingsSupported())
{
gpuRequest.Settings.DisableGdiAcceleration = true;
gpuRequest.Settings.DisablePresentation = true;
}
wsl::windows::common::hcs::ModifyComputeSystem(m_system.get(), wsl::shared::ToJsonW(gpuRequest).c_str());
// Also add 9p shares for the library directories.
// N.B. These are not hosted by the out-of-proc drvfs 9p server because the GPU shares
// should work even if drvfs is disabled.
auto addShare = [&](PCWSTR name, PCWSTR path) {
constexpr auto flags = (hcs::Plan9ShareFlags::ReadOnly | hcs::Plan9ShareFlags::AllowOptions);
wsl::windows::common::hcs::AddPlan9Share(m_system.get(), name, name, path, LX_INIT_UTILITY_VM_PLAN9_PORT, flags);
};
std::wstring path;
THROW_IF_FAILED(wil::ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\DriverStore\\FileRepository", path));
addShare(TEXT(LXSS_GPU_DRIVERS_SHARE), path.c_str());
// N.B. There are inbox and packaged versions of the Direct 3D libraries. The packaged
// versions take presidence by using overlayfs in the guest.
THROW_IF_FAILED(wil::ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\lxss\\lib", path));
if (wsl::windows::common::filesystem::FileExists(path.c_str()))
{
try
{
addShare(TEXT(LXSS_GPU_INBOX_LIB_SHARE), path.c_str());
m_enableInboxGpuLibs = true;
}
CATCH_LOG()
}
#ifdef WSL_GPU_LIB_PATH
path = TEXT(WSL_GPU_LIB_PATH);
#else
path = m_installPath / L"lib";
#endif
addShare(TEXT(LXSS_GPU_PACKAGED_LIB_SHARE), path.c_str());
}
// Asynchronously add drvfs devices if supported.
if (m_vmConfig.EnableHostFileSystemAccess)
{
std::promise<bool> initialResult;
m_drvfsInitialResult = initialResult.get_future();
auto guestDeviceLock = m_guestDeviceLock.lock_exclusive();
std::thread([this, guestDeviceLock = std::move(guestDeviceLock), initialResult = std::move(initialResult)]() mutable {
try
{
wsl::windows::common::wslutil::SetThreadDescription(L"InitializeDrvfs");
initialResult.set_value(InitializeDrvFsLockHeld(m_userToken.get()));
}
catch (...)
{
try
{
initialResult.set_exception(std::current_exception());
}
CATCH_LOG()
}
}).detach();
}
// Accept a connection from mini_init with a receive timeout so the service does not get stuck waiting for a response from the VM.
m_miniInitChannel = wsl::shared::SocketChannel{AcceptConnection(m_vmConfig.KernelBootTimeout), "mini_init", m_terminatingEvent.get()};
// Accept the connection from the Linux guest for notifications.
m_notifyChannel = AcceptConnection(m_vmConfig.KernelBootTimeout);
// Receive and parse the guest kernel version
ReadGuestCapabilities();
// Mount the system distro.
// N.B. If using SCSI, the system distro is added during VM creation.
switch (m_systemDistroDeviceType)
{
case LxMiniInitMountDeviceTypePmem:
m_systemDistroDeviceId = MountFileAsPersistentMemory(m_vmConfig.SystemDistroPath.c_str(), true);
break;
}
// Attempt to create and mount the swap vhd.
//
// N.B. This can fail if the target directory is compressed, encrypted, or if
// the user does not have write access.
ULONG swapLun = ULONG_MAX;
if ((m_systemDistroDeviceId != ULONG_MAX) && (m_vmConfig.SwapSizeBytes > 0))
{
try
{
{
// If no user-specified swap vhd file path was specified, use a
// path in the temp directory.
auto runAsUser = wil::impersonate_token(m_userToken.get());
if (m_vmConfig.SwapFilePath.empty())
{
m_vmConfig.SwapFilePath = m_tempPath / L"swap";
}
// Ensure the swap vhd ends with the vhdx file extension.
if (!wsl::windows::common::string::IsPathComponentEqual(
m_vmConfig.SwapFilePath.extension().native(), wsl::windows::common::wslutil::c_vhdxFileExtension))
{
m_vmConfig.SwapFilePath += wsl::windows::common::wslutil::c_vhdxFileExtension;
}
// Create the VHD with an additional page for swap overhead.
m_vmConfig.SwapSizeBytes += PAGE_SIZE;
auto result = wil::ResultFromException([&]() {
wsl::core::filesystem::CreateVhd(m_vmConfig.SwapFilePath.c_str(), m_vmConfig.SwapSizeBytes, &m_userSid.Sid, false, false);
m_swapFileCreated = true;
});
if (result == HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
{
auto handle = wsl::core::filesystem::OpenVhd(
m_vmConfig.SwapFilePath.c_str(), VIRTUAL_DISK_ACCESS_CREATE | VIRTUAL_DISK_ACCESS_METAOPS | VIRTUAL_DISK_ACCESS_GET_INFO);
wsl::core::filesystem::ResizeExistingVhd(handle.get(), m_vmConfig.SwapSizeBytes, RESIZE_VIRTUAL_DISK_FLAG_ALLOW_UNSAFE_VIRTUAL_SIZE);
}
else if (FAILED(result))
{
EMIT_USER_WARNING(wsl::shared::Localization::MessagedFailedToCreateSwapVhd(
m_vmConfig.SwapFilePath.c_str(), wsl::windows::common::wslutil::GetSystemErrorString(result).c_str()));
THROW_HR(result);
}
}
swapLun = AttachDiskLockHeld(m_vmConfig.SwapFilePath.c_str(), DiskType::VHD, MountFlags::None, {}, false, m_userToken.get());
}
CATCH_LOG()
}
// Validate that the requesting network mode is supported.
//
// N.B. This must be done before sending the initial configuration message because some guest
// behavior is determined by the networking mode.
ValidateNetworkingMode();
// Send the early configuration message.
wsl::shared::MessageWriter<LX_MINI_INIT_EARLY_CONFIG_MESSAGE> message(LxMiniInitMessageEarlyConfig);
message->SwapLun = swapLun;
message->SystemDistroDeviceType = m_systemDistroDeviceType;
message->SystemDistroDeviceId = m_systemDistroDeviceId;
message->PageReportingOrder = m_coldDiscardShiftSize;
message->MemoryReclaimMode = static_cast<LX_MINI_INIT_MEMORY_RECLAIM_MODE>(m_vmConfig.MemoryReclaim);
message->EnableDebugShell = m_vmConfig.EnableDebugShell;
message->EnableSafeMode = m_vmConfig.EnableSafeMode;
message->EnableDnsTunneling = m_vmConfig.EnableDnsTunneling;
message->DefaultKernel = m_defaultKernel;
message->KernelModulesDeviceId = m_kernelModulesDeviceId;
message.WriteString(message->HostnameOffset, wsl::windows::common::filesystem::GetLinuxHostName());
message.WriteString(message->KernelModulesListOffset, m_vmConfig.KernelModulesList);
message->DnsTunnelingIpAddress = m_vmConfig.DnsTunnelingIpAddress.value_or(0);
m_miniInitChannel.SendMessage<LX_MINI_INIT_EARLY_CONFIG_MESSAGE>(message.Span());
{
ExecutionContext context(Context::ConfigureNetworking);
// Accept the connection from the guest network service and create the channel.
wsl::core::GnsChannel gnsChannel(AcceptConnection(m_vmConfig.KernelBootTimeout));
// Create hvsocket connection for DNS tunneling if enabled.
wil::unique_socket dnsTunnelingSocket;
if (message->EnableDnsTunneling)
{
dnsTunnelingSocket = AcceptConnection(m_vmConfig.KernelBootTimeout);
}
// Record the start time of the networking engine initialization so the duration can be logged.
const auto startTime = std::chrono::steady_clock::now();
// For NAT networking, ensure the network can be created. If creating the network fails, fall back to
// virtio proxy networking mode.
wsl::windows::common::hcs::unique_hcn_network natNetwork;
if (m_vmConfig.NetworkingMode == NetworkingMode::Nat)
{
natNetwork = wsl::core::NatNetworking::CreateNetwork(m_vmConfig);
if (!natNetwork)
{
EMIT_USER_WARNING(wsl::shared::Localization::MessageNetworkInitializationFailedFallback2(
ToString(m_vmConfig.NetworkingMode), ToString(NetworkingMode::VirtioProxy)));
m_vmConfig.NetworkingMode = NetworkingMode::VirtioProxy;
}
}
// Create and initialize the networking engine.
const auto result = wil::ResultFromException(WI_DIAGNOSTICS_INFO, [&] {
if (m_vmConfig.NetworkingMode == NetworkingMode::Mirrored)
{
m_networkingEngine = std::make_unique<wsl::core::MirroredNetworking>(
m_system.get(), std::move(gnsChannel), m_vmConfig, m_runtimeId, std::move(dnsTunnelingSocket));
}
else if (m_vmConfig.NetworkingMode == NetworkingMode::Nat)
{
WI_ASSERT(natNetwork);
m_networkingEngine = std::make_unique<wsl::core::NatNetworking>(
m_system.get(), std::move(natNetwork), std::move(gnsChannel), m_vmConfig, std::move(dnsTunnelingSocket));
}
else if (m_vmConfig.NetworkingMode == NetworkingMode::VirtioProxy)
{
wsl::core::VirtioNetworkingFlags flags = wsl::core::VirtioNetworkingFlags::Ipv6;
WI_SetFlagIf(flags, wsl::core::VirtioNetworkingFlags::LocalhostRelay, m_vmConfig.EnableLocalhostRelay);
WI_SetFlagIf(flags, wsl::core::VirtioNetworkingFlags::DnsTunnelingSocket, m_vmConfig.EnableDnsTunneling);
m_networkingEngine = std::make_unique<wsl::core::VirtioNetworking>(
std::move(gnsChannel), flags, LX_INIT_RESOLVCONF_FULL_HEADER, m_guestDeviceManager, m_userToken, std::move(dnsTunnelingSocket));
}
else if (m_vmConfig.NetworkingMode == NetworkingMode::Bridged)
{
m_networkingEngine = std::make_unique<wsl::core::BridgedNetworking>(m_system.get(), m_vmConfig);
}
else
{
WI_ASSERT(m_vmConfig.NetworkingMode == NetworkingMode::None);
}
if (m_networkingEngine)
{
m_networkingEngine->Initialize();
}
});
// Find the interface type of the host interface that is most likely to give Internet connectivity
const auto bestInterfaceIndex = wsl::core::networking::GetBestInterface();
MIB_IFROW row{};
row.dwIndex = bestInterfaceIndex;
IFTYPE bestInterfaceType{};
// Ignore failures
if (row.dwIndex != 0 && SUCCEEDED_WIN32(GetIfEntry(&row)))
{
bestInterfaceType = row.dwType;
}
const auto endTime = std::chrono::steady_clock::now();
// Log telemetry on the VM initialization including some of its key settings
WSL_LOG_TELEMETRY(
"WslCoreVmInitialize",
PDT_ProductAndServicePerformance,
TraceLoggingValue(m_runtimeId, "vmId"),
TraceLoggingValue(ToString(m_vmConfig.NetworkingMode), "networkingMode"),
TraceLoggingValue(m_vmConfig.FirewallConfig.Enabled(), "firewallEnabled"),
TraceLoggingValue(m_vmConfig.EnableDnsTunneling, "dnsTunnelingEnabled"),
TraceLoggingValue(
m_vmConfig.DnsTunnelingIpAddress.has_value()
? wsl::windows::common::string::IntegerIpv4ToWstring(m_vmConfig.DnsTunnelingIpAddress.value()).c_str()
: L"",
"dnsTunnelingIpAddress"),
TraceLoggingValue(bestInterfaceType, "bestInterfaceType"),
TraceLoggingValue(result, "result"),
TraceLoggingValue((std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime)).count(), "durationMs"));
if (FAILED(result))
{
const auto* context = ExecutionContext::Current();
if (context != nullptr)
{
// We already have a specialized error message, display it to the user.
const auto& currentError = context->ReportedError();
if (currentError.has_value())
{
auto strings = wsl::windows::common::wslutil::ErrorToString(currentError.value());
EMIT_USER_WARNING(Localization::MessageErrorCode(strings.Message, strings.Code));
}
}
// If something failed during initialization that indicates a dependent service is not running,
// inform the user to install the Virtual Machine Platform optional component.
if (wsl::core::networking::IsNetworkErrorForMissingServices(result) &&
!wsl::windows::common::wslutil::IsVirtualMachinePlatformInstalled())
{
wsl::windows::common::notifications::DisplayOptionalComponentsNotification();
EMIT_USER_WARNING(Localization::MessageVirtualMachinePlatformNotInstalled());
}
// Fall back to no networking.
EMIT_USER_WARNING(wsl::shared::Localization::MessageNetworkInitializationFailedFallback2(
ToString(m_vmConfig.NetworkingMode), ToString(NetworkingMode::None)));
m_vmConfig.NetworkingMode = NetworkingMode::None;
m_networkingEngine.reset();
}
}
// Perform additional initialization.
InitializeGuest();
}
WslCoreVm::~WslCoreVm() noexcept
{
TraceLoggingActivity<g_hTraceLoggingProvider, MICROSOFT_KEYWORD_MEASURES> activity;
TraceLoggingWriteStart(
activity,
"TerminateVmStart",
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance),
TraceLoggingValue(m_runtimeId, "vmId"));
m_networkingEngine.reset();
auto lock = m_lock.lock_exclusive();
if (m_drvfsInitialResult.valid())
{
try
{
m_drvfsInitialResult.get();
}
CATCH_LOG()
}
// Clear out the exit callback.
{
auto exitLock = m_exitCallbackLock.lock_exclusive();
m_onExit = nullptr;
// Signal that the vm is terminating
// N.B. This might have already been signaled if the VM exited abnormally.
m_terminatingEvent.SetEvent();
}
if (m_system)
{
bool unexpectedTerminate = m_vmExitEvent.is_signaled();
bool forcedTerminate = false;
// Close the socket to mini_init. This will cause mini_init to break out
// of its message processing loop and perform a clean shutdown.
m_miniInitChannel.Close();
if (!unexpectedTerminate)
{
// Wait to receive the notification that the VM has exited.
forcedTerminate = !m_vmExitEvent.wait(UTILITY_VM_SHUTDOWN_TIMEOUT);
// If the notification did not arrive within the timeout, the VM is
// forcefully terminated.
if (forcedTerminate)
{
try
{
wsl::windows::common::hcs::TerminateComputeSystem(m_system.get());
}
CATCH_LOG()
}
}
m_vmExitEvent.wait(UTILITY_VM_TERMINATE_TIMEOUT);
TraceLoggingWriteTagged(
activity,
"TerminateVm",
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance),
TraceLoggingValue(WSL_PACKAGE_VERSION, "wslVersion"),
TraceLoggingValue(m_runtimeId, "vmId"),
TraceLoggingValue(forcedTerminate, "forceTerminate"),
TraceLoggingValue(unexpectedTerminate, "unexpectedTerminate"),
TraceLoggingValue(m_vmExitEvent.is_signaled(), "terminationCallbackReceived"),
TraceLoggingValue(m_exitDetails.c_str(), "exitDetails"));
}
// Wait for the distro exit callback thread to exit.
// The thread might not have been started, in that case joinable() returns false.
if (m_distroExitThread.joinable())
{
m_distroExitThread.join();
}
if (m_virtioFsThread.joinable())
{
m_virtioFsThread.join();
}
if (m_crashDumpCollectionThread.joinable())
{
m_crashDumpCollectionThread.join();
}
// Close the handle to the VM. This will wait for any outstanding callbacks.
m_system.reset();
// This loops helps against a potential crash in build <= Windows 11 22H2.
for (const auto& e : m_plan9Servers)
{
LOG_IF_FAILED(e.second->Teardown());
}
// Shutdown virtio device hosts.
m_guestDeviceManager.reset();
// Call RevokeVmAccess on each VHD that was added to the utility VM. This
// ensures that the ACL on the VHD does not grow unbounded.
std::for_each(m_attachedDisks.begin(), m_attachedDisks.end(), [&](const auto& Entry) {
if ((Entry.first.Type == DiskType::PassThrough) && (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::Online)))
{
RestorePassthroughDiskState(Entry.first.Path.c_str());
}
if (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::AccessGranted))
{
try
{
wsl::windows::common::hcs::RevokeVmAccess(m_machineId.c_str(), Entry.first.Path.c_str());
}
CATCH_LOG()
}
});
// Delete the swap vhd if one was created.
if (m_swapFileCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
LOG_IF_WIN32_BOOL_FALSE(DeleteFileW(m_vmConfig.SwapFilePath.c_str()));
}
CATCH_LOG()
}
// Delete the temp folder if it was created.
if (m_tempDirectoryCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
wil::RemoveDirectoryRecursive(m_tempPath.c_str());
}
CATCH_LOG()
}
// Delete the mstsc.exe local devices key if one was created.
if (m_localDevicesKeyCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
const auto userKey = wsl::windows::common::registry::OpenCurrentUser();
const auto key = wsl::windows::common::registry::CreateKey(userKey.get(), c_localDevicesKey, KEY_SET_VALUE);
THROW_IF_WIN32_ERROR(::RegDeleteKeyValueW(key.get(), nullptr, m_machineId.c_str()));
}
CATCH_LOG()
}
WSL_LOG("TerminateVmStop");
}
wil::unique_socket WslCoreVm::AcceptConnection(_In_ DWORD ReceiveTimeout, _In_ const std::source_location& Location) const
{
auto socket = hvsocket::CancellableAccept(m_listenSocket.get(), m_vmConfig.KernelBootTimeout, m_terminatingEvent.get(), Location);
THROW_HR_IF(E_ABORT, !socket.has_value());
if (ReceiveTimeout != 0)
{
THROW_LAST_ERROR_IF(setsockopt(socket->get(), SOL_SOCKET, SO_RCVTIMEO, (const char*)&ReceiveTimeout, sizeof(ReceiveTimeout)) == SOCKET_ERROR);
}
return std::move(socket.value());
}
_Requires_lock_held_(m_guestDeviceLock)
void WslCoreVm::AddDrvFsShare(_In_ bool Admin, _In_ HANDLE UserToken)
{
THROW_HR_IF(HCS_E_TERMINATED, !m_system);
// Allow the Plan 9 server to create NT symlinks.
//
// N.B. This may fail for unelevated users, however symlink creation will
// succeed even without this privilege if developer mode is enabled.
wsl::windows::common::security::EnableTokenPrivilege(UserToken, SE_CREATE_SYMBOLIC_LINK_NAME);
// Set the 9p port and virtio tag.
const UINT32 port = Admin ? LX_INIT_UTILITY_VM_PLAN9_DRVFS_ADMIN_PORT : LX_INIT_UTILITY_VM_PLAN9_DRVFS_PORT;
const PCWSTR tag = Admin ? TEXT(LX_INIT_DRVFS_ADMIN_VIRTIO_TAG) : TEXT(LX_INIT_DRVFS_VIRTIO_TAG);
AddPlan9Share(
TEXT(LX_INIT_UTILITY_VM_DRVFS_SHARE_NAME), L"\\\\?", port, (hcs::Plan9ShareFlags::AllowOptions | hcs::Plan9ShareFlags::AllowSubPaths), UserToken, tag);
const auto virtiofsInitialized = Admin ? m_adminDrvfsToken.is_valid() : m_drvfsToken.is_valid();
if (m_vmConfig.EnableVirtioFs && !virtiofsInitialized)
{
// Add virtiofs devices associating indices with paths from the fixed drive bitmap. These devices support
// multiple mounts in the guest, so this only needs to be done once.
auto fixedDrives = wsl::windows::common::filesystem::EnumerateFixedDrives(UserToken).first;
while (fixedDrives != 0)
{
ULONG index;
WI_VERIFY(_BitScanForward(&index, fixedDrives) != FALSE);
const wchar_t fixedDrivePath[] = {gsl::narrow_cast<wchar_t>(L'A' + index), L':', L'\\', L'\0'};
AddVirtioFsShare(Admin, fixedDrivePath, TEXT(LX_INIT_DEFAULT_PLAN9_MOUNT_OPTIONS), UserToken);
fixedDrives ^= (1 << index);
}
}
}
_Requires_lock_held_(m_guestDeviceLock)
void WslCoreVm::AddPlan9Share(
_In_ PCWSTR AccessName, _In_ PCWSTR Path, [[maybe_unused]] _In_ UINT32 Port, _In_ hcs::Plan9ShareFlags Flags, _In_ HANDLE UserToken, _In_opt_ PCWSTR VirtIoTag)
{
bool addNewDevice = false;
wil::com_ptr<IPlan9FileSystem> server;
{
auto revert = wil::impersonate_token(UserToken);
// This is called from AddDrvFsShare, which is called from InitializeDrvFs, so m_guestDeviceLock is
// already held.
if (m_vmConfig.EnableVirtio9p)
{
server = m_guestDeviceManager->GetRemoteFileSystem(__uuidof(p9fs::Plan9FileSystem), VirtIoTag);
}
else
{
const auto existingServer = m_plan9Servers.find(Port);
if (existingServer != m_plan9Servers.end())
{
server = existingServer->second;
}
}
if (!server)
{
server = wsl::windows::common::wslutil::CreateComServerAsUser<p9fs::Plan9FileSystem, IPlan9FileSystem>(UserToken);
if (m_vmConfig.EnableVirtio9p)
{
m_guestDeviceManager->AddRemoteFileSystem(__uuidof(p9fs::Plan9FileSystem), VirtIoTag, server);
// Start with one device to handle the first mount request. After
// each mount, the Plan9 file-system will request additional
// devices via the IPlan9FileSystemHost::NotifyAllDevicesInUse
// callback.
addNewDevice = true;
}
else
{
THROW_IF_FAILED(server->Init(&m_runtimeId, Port));
THROW_IF_FAILED(server->Resume());
m_plan9Servers.insert(std::make_pair(Port, server));
}
}
HRESULT result = server->AddSharePath(AccessName, Path, static_cast<UINT32>(Flags));
if (result == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS))
{
result = S_OK;
}
THROW_IF_FAILED(result);
}
if (addNewDevice)
{
// This requires more privileges than the user may have, so impersonation is disabled.
(void)m_guestDeviceManager->AddNewDevice(VIRTIO_PLAN9_DEVICE_ID, server, VirtIoTag);
}
}
ULONG WslCoreVm::AttachDisk(_In_ PCWSTR Disk, _In_ DiskType Type, _In_ std::optional<ULONG> Lun, _In_ bool IsUserDisk, _In_ HANDLE UserToken)
{
auto lock = m_lock.lock_exclusive();
return AttachDiskLockHeld(Disk, Type, MountFlags::None, Lun, IsUserDisk, UserToken);
}
ULONG WslCoreVm::AttachDiskLockHeld(
_In_ PCWSTR Disk, _In_ DiskType Type, _In_ MountFlags Flags, _In_ std::optional<ULONG> Lun, _In_ bool IsUserDisk, _In_opt_ HANDLE UserToken)
{
ExecutionContext context(Context::MountDisk);
Lun = ReserveLun(Lun);
// Set a scope exit variable to perform cleanup if attaching the disk fails.
DiskStateFlags diskFlags{};
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&] {
FreeLun(Lun.value());
if (WI_IsFlagSet(diskFlags, DiskStateFlags::AccessGranted))
{
wsl::windows::common::hcs::RevokeVmAccess(m_machineId.c_str(), Disk);
}
if (WI_IsFlagSet(diskFlags, DiskStateFlags::Online))
{
const auto diskHandle = wsl::windows::common::disk::OpenDevice(Disk, GENERIC_READ | GENERIC_WRITE, m_vmConfig.MountDeviceTimeout);
wsl::windows::common::disk::SetOnline(diskHandle.get(), false, m_vmConfig.MountDeviceTimeout);
}
});
try
{
// Check if the disk is already attached.
const auto found = m_attachedDisks.find({Type, Disk});
if (Type == DiskType::PassThrough)
{
if (found != m_attachedDisks.end())
{
THROW_HR_WITH_USER_ERROR(WSL_E_DISK_ALREADY_ATTACHED, Localization::MessageDiskAlreadyAttached(Disk));
}
// Grant the VM access to the disk.
GrantVmWorkerProcessAccessToDisk(Disk, UserToken);
WI_SetFlag(diskFlags, DiskStateFlags::AccessGranted);
// Set the disk online if needed.
//
// N.B. The disk handle must be closed prior to adding the disk to the VM.
{
const auto diskHandle =
wsl::windows::common::disk::OpenDevice(Disk, GENERIC_READ | GENERIC_WRITE, m_vmConfig.MountDeviceTimeout);
if (wsl::windows::common::disk::IsDiskOnline(diskHandle.get()))
{
wsl::windows::common::disk::SetOnline(diskHandle.get(), false, m_vmConfig.MountDeviceTimeout);
WI_SetFlag(diskFlags, DiskStateFlags::Online);
}
}
// Add the disk to the VM.
wsl::shared::retry::RetryWithTimeout<void>(
std::bind(wsl::windows::common::hcs::AddPassThroughDisk, m_system.get(), Disk, Lun.value()),
wsl::windows::common::disk::c_diskOperationRetry,
std::chrono::milliseconds(m_vmConfig.MountDeviceTimeout),
[]() { return wil::ResultFromCaughtException() == HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION); });
}
else
{
if (found != m_attachedDisks.end())
{
// Prevent user from launching a distro vhd after manually mounting it; otherwise, return the LUN of the mounted disk.
THROW_HR_IF(WSL_E_USER_VHD_ALREADY_ATTACHED, found->first.User);
return found->second.Lun;
}