### Build and Serve Documentation with MkDocs Source: https://github.com/microsoft/wsl/blob/master/doc/README.md This snippet installs the required Python packages for documentation generation and starts a local development server. It requires Python and pip to be installed on the host system. ```shell $ pip install mkdocs mkdocs-mermaid2-plugin $ mkdocs serve ``` -------------------------------- ### Install x64 .NET 6.0 Runtime for ARM64 Development Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Installs the x64 .NET 6.0 runtime required by WiX on ARM64 Windows systems. This ensures compatibility as WiX is an x64 binary. The script downloads the official .NET install script and then executes it to install the specified runtime. ```powershell # Download the official dotnet-install script Invoke-WebRequest -Uri "https://dot.net/v1/dotnet-install.ps1" -OutFile "$env:TEMP\dotnet-install.ps1" # Install the x64 .NET 6.0 runtime powershell -ExecutionPolicy Bypass -File "$env:TEMP\dotnet-install.ps1" -Channel 6.0 -Runtime dotnet -Architecture x64 -InstallDir "C:\Program Files\dotnet\x64" ``` -------------------------------- ### Deploy WSL using MSI Package or PowerShell Script Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Provides methods for deploying the built WSL. It includes installing the generated MSI package directly or using a PowerShell script for automated deployment. Options for deploying to a Hyper-V virtual machine are also detailed. ```powershell powershell tools\deploy\deploy-to-host.ps1 powershell tools\deploy\deploy-to-vm.ps1 -VmName -Username -Password ``` -------------------------------- ### Run WSL Unit Tests Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Executes the unit tests for WSL. The `test.bat` script is used, and various options are shown for filtering tests by name, specifying the WSL version, and skipping package installation for faster execution. ```bash bin\\\test.bat bin\\\test.bat /name:*UnitTest* bin\\\test.bat /name::: bin\x64\debug\test.bat /name:UnitTests::UnitTests::ModernInstall bin\x64\debug\test.bat -Version 1 wsl --set-default test_distro bin\x64\debug\test.bat /name:*UnitTest* -f ``` -------------------------------- ### Define a TAEF Test Class and Method Source: https://github.com/microsoft/wsl/blob/master/test/README.md Shows the structure for creating a test class and a test method using TAEF macros. It includes an example of verifying output equality using the VERIFY_ARE_EQUAL macro. ```cpp #include "WexTestClass.h" #include "Common.h" #define INLINE_TEST_METHOD_MARKUP namespace ExampleTest { class ExampleTest { TEST_CLASS(ExampleTest) TEST_METHOD(HelloWorldTest) { std::wstring outputExpected = L"Linux on Windows Rocks!\n"; auto [output, __] = LxsstuLaunchWslAndCaptureOutput(L"echo Linux on Windows Rocks!"); VERIFY_ARE_EQUAL(output, outputExpected); } }; } ``` -------------------------------- ### Programmatic WSL Interaction via ILxssUserSession COM Interface Source: https://context7.com/microsoft/wsl/llms.txt This C++ code snippet demonstrates how to interact with WSL programmatically using the `ILxssUserSession` COM interface. It shows the initialization of COM, creation of the WSL session object, and an example of creating a distribution instance. This interface is used internally by `wsl.exe` and provides access to WSL functionalities. ```cpp #include #include // GUID definitions from wslservice.idl const GUID CLSID_LxssUserSession = {0xa9b7a1b9, 0x0671, 0x405c, {0x95, 0xf1, 0xe0, 0x61, 0x2c, 0xb4, 0xce, 0x7e}}; const GUID IID_ILxssUserSession = {0x38541BDC, 0xF54F, 0x4CEB, {0x85, 0xD0, 0x37, 0xF0, 0xF3, 0xD2, 0x61, 0x7E}}; // Key methods available on ILxssUserSession: // - CreateInstance(): Launch a WSL distribution // - CreateLxProcess(): Launch a process inside a distribution // - RegisterDistribution(): Register a new WSL distribution // - UnregisterDistribution(): Remove a distribution // - EnumerateDistributions(): List all registered distributions // - GetDefaultDistribution(): Get the default distribution GUID // - SetDefaultDistribution(): Set the default distribution // - Shutdown(): Terminate all WSL distributions // - ExportDistribution(): Export a distribution to file // - AttachDisk() / DetachDisk() / MountDisk(): Disk management // Example: Initialize COM and get WSL session HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) return hr; ILxssUserSession* pSession = nullptr; hr = CoCreateInstance(CLSID_LxssUserSession, NULL, CLSCTX_LOCAL_SERVER, IID_ILxssUserSession, (void**)&pSession); if (SUCCEEDED(hr)) { LXSS_ERROR_INFO errorInfo = {0}; // Create/start a distribution instance hr = pSession->CreateInstance( &distroGuid, // Distribution GUID (NULL for default) LXSS_CREATE_INSTANCE_FLAGS_ALLOW_FS_UPGRADE, &errorInfo ); // Clean up pSession->Release(); } CoUninitialize(); ``` -------------------------------- ### Start and Stop WSL ETL Tracing with WPR Source: https://github.com/microsoft/wsl/blob/master/doc/docs/debugging.md This snippet demonstrates how to start and stop the collection of ETL traces for WSL debugging using the Windows Performance Recorder (WPR) tool. It includes steps for reproducing the issue and stopping the trace to generate a log file. ```bash wpr -start wsl.wprp -filemode [reproduce the issue] wpr -stop logs.ETL ``` -------------------------------- ### WSL Command Line Interface Operations Source: https://context7.com/microsoft/wsl/llms.txt This section covers common operations using the `wsl.exe` command-line tool. It includes commands for installing, listing, running, configuring, and managing WSL distributions, as well as disk mounting and unmounting. These commands are essential for interacting with Linux environments within Windows. ```powershell # Install WSL with default Ubuntu distribution wsl --install # Install a specific distribution wsl --install -d Debian # List all installed distributions with their status wsl --list --verbose # Output: # NAME STATE VERSION # * Ubuntu Running 2 # Debian Stopped 2 # Run a command in the default distribution wsl ls -la /home # Run a command in a specific distribution wsl -d Ubuntu -- cat /etc/os-release # Set the default WSL version for new distributions wsl --set-default-version 2 # Convert an existing distribution between WSL1 and WSL2 wsl --set-version Ubuntu 2 # Set the default distribution wsl --set-default Debian # Shutdown all running distributions wsl --shutdown # Terminate a specific distribution wsl --terminate Ubuntu # Export a distribution to a tar file wsl --export Ubuntu C:\backup\ubuntu-backup.tar # Import a distribution from a tar file wsl --import MyUbuntu C:\WSL\MyUbuntu C:\backup\ubuntu-backup.tar # Import with VHD format (WSL2 only) wsl --import MyUbuntu C:\WSL\MyUbuntu C:\backup\ubuntu.vhdx --vhd # Unregister and delete a distribution wsl --unregister MyUbuntu # Mount a disk in WSL2 wsl --mount \\.\PHYSICALDRIVE1 --partition 1 # Unmount a disk wsl --unmount \\.\PHYSICALDRIVE1 # Check WSL status and version info wsl --status # Output: # Default Distribution: Ubuntu # Default Version: 2 # WSL version: 2.0.9.0 # Kernel version: 5.15.133.1-1 ``` -------------------------------- ### Generate Cross-Architecture MSIX Bundle Source: https://github.com/microsoft/wsl/blob/master/msixinstaller/CMakeLists.txt Creates an MSIX bundle by generating a mapping file and executing makeappx.exe. This process is triggered only when both x64 and ARM64 installer artifacts are present, and it includes signing the final bundle. ```cmake if ((TARGET_PLATFORM STREQUAL "arm64" AND EXISTS ${X64_BUNDLE_PATH}) OR (TARGET_PLATFORM STREQUAL "x64" AND EXISTS ${ARM64_BUNDLE_PATH})) set(PACKAGE_NAME "Microsoft.WSL_${PACKAGE_VERSION}") set(BUNDLE_DIR ${CMAKE_SOURCE_DIR}/bundle/${CMAKE_BUILD_TYPE}) set(BUNDLE_MAPPINGS_FILE ${BUNDLE_DIR}/mappings.ini) set(OUTPUT_BUNDLE ${BUNDLE_DIR}/${PACKAGE_NAME}_x64_ARM64.msixbundle) file(MAKE_DIRECTORY ${BUNDLE_DIR}) file(WRITE ${BUNDLE_MAPPINGS_FILE} "[Files]\n") file(APPEND ${BUNDLE_MAPPINGS_FILE} "\"${X64_BUNDLE_PATH}\"" " \"${PACKAGE_NAME}_x64.msix\"\n") file(APPEND ${BUNDLE_MAPPINGS_FILE} "\"${ARM64_BUNDLE_PATH}\"" " \"${PACKAGE_NAME}_ARM64.msix\"\n") add_custom_command( OUTPUT ${OUTPUT_BUNDLE} COMMAND makeappx.exe bundle -f ${BUNDLE_MAPPINGS_FILE} -bv ${PACKAGE_VERSION} -o -p ${OUTPUT_BUNDLE} COMMAND ${PACKAGE_SIGN_COMMAND} ${OUTPUT_BUNDLE} COMMAND ${CMAKE_COMMAND} -E touch "${CMAKE_CURRENT_BINARY_DIR}/CmakeFiles/bundle" VERBATIM DEPENDS ${CMAKE_SOURCE_DIR}/bin/X64/${CMAKE_BUILD_TYPE}/installer.msix ${CMAKE_SOURCE_DIR}/bin/arm64/${CMAKE_BUILD_TYPE}/installer.msix ) add_custom_target(bundle DEPENDS ${OUTPUT_BUNDLE}) add_dependencies(bundle msixinstallerpackage) endif() ``` -------------------------------- ### Open WSL Debug Shell Source: https://github.com/microsoft/wsl/blob/master/doc/docs/debugging.md This snippet demonstrates how to access the WSL debug shell, which is necessary for debugging certain WSL processes like `gns` or `mini_init` that are not directly accessible from within WSL distributions. It also shows how to install gdb within the debug shell. ```bash wsl --debug-shell tdnf install gdb ``` -------------------------------- ### Define MSIX Installer Package Target Source: https://github.com/microsoft/wsl/blob/master/msixinstaller/CMakeLists.txt Configures the MSIX installer package by defining dependencies and invoking the add_appx_target macro. It conditionally includes the MSI installer based on the WSL_BUILD_THIN_PACKAGE variable. ```cmake set(DEPENDENCIES "wsl.exe;wslinstaller.exe;wslinstallerproxystub.dll") if (NOT "${WSL_BUILD_THIN_PACKAGE}") list(APPEND DEPENDENCIES "wsl.msi") endif() add_appx_target(msixinstallerpackage "${DEPENDENCIES}" "${CMAKE_CURRENT_LIST_DIR}/AppxManifest.in" "${BIN}/installer.msix" "wsl;wslinstaller;msipackage;wslinstallerproxystub") ``` -------------------------------- ### Configure WSL MSI Packaging with CMake Source: https://github.com/microsoft/wsl/blob/master/msipackage/CMakeLists.txt This snippet defines the build environment for creating a Windows MSI installer. It collects Windows and Linux binaries, sets up dependencies, and defines a custom target to trigger the WiX build process. ```cmake set(BIN ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CMAKE_BUILD_TYPE}) if(DEFINED PACKAGE_INPUT_DIR) message(STATUS "Using signed binaries from ${PACKAGE_INPUT_DIR} for MSI packaging") else() set(PACKAGE_INPUT_DIR ${BIN}) endif() set(WINDOWS_BINARIES wsl.exe;wslg.exe;wslhost.exe;wslrelay.exe;wslservice.exe;wslserviceproxystub.dll;wslinstall.dll) set(BINARIES_DEPENDENCIES) foreach(binary ${WINDOWS_BINARIES}) list(APPEND BINARIES_DEPENDENCIES "${PACKAGE_INPUT_DIR}/${binary}") endforeach() add_custom_command( OUTPUT ${OUTPUT_PACKAGE} COMMAND ${WIX_SOURCE_DIR}/wix.exe build ${PACKAGE_WIX} -o ${OUTPUT_PACKAGE} -arch ${TARGET_PLATFORM} -dcl ${COMPRESSION} -cc ${CAB_CACHE} -pdbtype none DEPENDS ${PACKAGE_WIX} ${BINARIES_DEPENDENCIES} ) add_custom_target(msipackage DEPENDS ${OUTPUT_PACKAGE}) ``` -------------------------------- ### Configure WSL Installer Executable with CMake Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslinstaller/exe/CMakeLists.txt This CMake script defines the source files and headers for the wslinstaller executable. It sets up build dependencies, linker flags for COM object mapping, and links necessary libraries for the Windows environment. ```cmake set(SOURCES ServiceMain.cpp WslInstallerFactory.cpp WslInstaller.cpp main.rc) set (HEADERS WslInstallerFactory.h WslInstaller.h) include_directories(${CMAKE_BINARY_DIR}/src/windows/wslinstaller/inc/${TARGET_PLATFORM}/${CMAKE_BUILD_TYPE}) add_executable(wslinstaller ${SOURCES} ${HEADERS}) add_dependencies(wslinstaller wslinstalleridl) set_target_properties(wslinstaller PROPERTIES LINK_FLAGS "/merge:minATL=.rdata /include:__minATLObjMap_WslInstaller_COM") target_link_libraries(wslinstaller ${COMMON_LINK_LIBRARIES} ${MSI_LINK_LIBRARIES} common legacy_stdio_definitions) target_precompile_headers(wslinstaller REUSE_FROM common) set_target_properties(wslinstaller PROPERTIES FOLDER windows) ``` -------------------------------- ### Determine LLVM Installation Directory (CMake) Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Sets the LLVM installation directory based on the host system's processor architecture and the determined Visual Studio installation path. It checks for the existence of the LLVM bin directory and fails if not found, prompting the user to install the C++ Clang Compiler for Windows. ```cmake if("${CMAKE_HOST_SYSTEM_PROCESSOR}" STREQUAL "AMD64") set(LLVM_INSTALL_DIR "${VS_INSTALL_DIR}/VC/Tools/Llvm/x64/bin") else() set(LLVM_INSTALL_DIR "${VS_INSTALL_DIR}/VC/Tools/Llvm/${CMAKE_HOST_SYSTEM_PROCESSOR}/bin") endif() if (NOT EXISTS ${LLVM_INSTALL_DIR}) message(FATAL_ERROR "C++ Clang Compiler for Windows is not installed at ${LLVM_INSTALL_DIR}. Please install it from the Visual Studio Installer.") endif() ``` -------------------------------- ### Configure wslinstall Shared Library with CMake Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslinstall/CMakeLists.txt This CMake script defines the wslinstall shared library, sets its source files, and configures include directories. It also links the library against required system dependencies and common project libraries. ```cmake set(SOURCES DllMain.cpp version.rc) add_library(wslinstall SHARED ${SOURCES} wslinstall.def) target_include_directories(wslinstall PUBLIC ${CMAKE_CURRENT_LIST_DIR}) set_target_properties(wslinstall PROPERTIES FOLDER windows) target_precompile_headers(wslinstall REUSE_FROM common) target_link_libraries(wslinstall ${COMMON_LINK_LIBRARIES} ${MSI_LINK_LIBRARIES} common legacy_stdio_definitions Crypt32.lib sfc.lib) ``` -------------------------------- ### Specify WSL ETL Trace Profile with WPR Source: https://github.com/microsoft/wsl/blob/master/doc/docs/debugging.md This snippet shows how to use specific tracing profiles within the `wsl.wprp` file when starting an ETL trace with WPR. This allows for more targeted logging, such as focusing on networking or storage issues. ```bash wpr -start wsl.wprp!WSL-Networking -filemode ``` -------------------------------- ### Set DOTNET_ROOT_X64 Environment Variable Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Configures the DOTNET_ROOT_X64 environment variable to point to the installed x64 .NET 6.0 runtime directory. This allows the system to locate the necessary .NET binaries for WiX. It provides options for setting the variable for the current session or permanently for the user. ```powershell # Set for the current session $env:DOTNET_ROOT_X64 = "C:\Program Files\dotnet\x64" # Set permanently for your user [System.Environment]::SetEnvironmentVariable("DOTNET_ROOT_X64", "C:\Program Files\dotnet\x64", "User") ``` -------------------------------- ### Build and Deploy WSL from Source Source: https://context7.com/microsoft/wsl/llms.txt Commands to clone, configure, build, and deploy the WSL project using CMake and PowerShell. It includes steps for generating build solutions for different architectures and running automated unit tests. ```powershell winget install Kitware.CMake git clone https://github.com/microsoft/WSL.git cd WSL cmake . cmake --build . powershell tools\deploy\deploy-to-host.ps1 bin\x64\debug\test.bat /name:*UnitTest* ``` -------------------------------- ### Configure WSL for Faster Development Builds Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Speeds up the WSL development cycle by enabling faster builds and deployments. This involves copying a sample configuration file and uncommenting a line to specify a custom development binary path. Additional options for building smaller packages and automatic deployment are also mentioned. ```bash copy UserConfig.cmake.sample UserConfig.cmake # set(WSL_DEV_BINARY_PATH "C:/wsldev") ``` -------------------------------- ### Interact with WSL Distributions using wslapi.dll (C++) Source: https://context7.com/microsoft/wsl/llms.txt This C++ code snippet demonstrates how to use the wslapi.dll to check if a distribution is registered, retrieve its configuration, modify settings, launch processes within a distribution, register a new distribution from a tar file, and unregister a distribution. It requires linking against wslapi.lib. ```cpp #include #include #pragma comment(lib, "wslapi.lib") int main() { // Check if a distribution is registered BOOL isRegistered = WslIsDistributionRegistered(L"Ubuntu"); if (!isRegistered) { printf("Ubuntu is not installed\n"); return 1; } // Get distribution configuration ULONG version, defaultUid, flags; PSTR* defaultEnv; ULONG envCount; HRESULT hr = WslGetDistributionConfiguration( L"Ubuntu", &version, // WSL version (1 or 2) &defaultUid, // Default user ID &flags, // Distribution flags &defaultEnv, // Default environment variables &envCount ); if (SUCCEEDED(hr)) { printf("WSL Version: %lu\n", version); printf("Default UID: %lu\n", defaultUid); // Flags: LXSS_DISTRO_FLAGS_ENABLE_INTEROP (0x1) // LXSS_DISTRO_FLAGS_APPEND_NT_PATH (0x2) // LXSS_DISTRO_FLAGS_ENABLE_DRIVE_MOUNTING (0x4) } // Configure distribution settings hr = WslConfigureDistribution( L"Ubuntu", 1000, // Default UID (usually 1000 for first user) LXSS_DISTRO_FLAGS_ENABLE_INTEROP | LXSS_DISTRO_FLAGS_APPEND_NT_PATH | LXSS_DISTRO_FLAGS_ENABLE_DRIVE_MOUNTING ); // Launch a process in WSL DWORD exitCode; hr = WslLaunch( L"Ubuntu", // Distribution name L"ls -la /home", // Command to run FALSE, // Use current directory GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE), &exitCode ); if (SUCCEEDED(hr)) { printf("Command exited with code: %lu\n", exitCode); } // Register a new distribution from a tar file hr = WslRegisterDistribution( L"MyCustomDistro", L"C:\\distros\\custom-rootfs.tar.gz" ); // Unregister a distribution hr = WslUnregisterDistribution(L"MyCustomDistro"); return 0; } ``` -------------------------------- ### Find Visual Studio Installation Directory (CMake Function) Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt A CMake function to locate the Visual Studio installation directory using `vswhere.exe`. It searches within specified version ranges and requires the LLVM Clang component. It prioritizes VS2022 and falls back to VS2026 if necessary, issuing a warning if VS2022 is not found. ```cmake function(find_vs_install_dir VERSION_RANGE OUTPUT_VAR) execute_process( COMMAND "${VSWHERE_SOURCE_DIR}/vswhere.exe" -version "${VERSION_RANGE}" -products * -requires Microsoft.VisualStudio.Component.VC.Llvm.Clang -property installationPath -prerelease -latest OUTPUT_VARIABLE _vs_install_dir OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY ) set(${OUTPUT_VAR} "${_vs_install_dir}" PARENT_SCOPE) endfunction() find_vs_install_dir("[17.0,18.0)" VS_INSTALL_DIR) if (NOT VS_INSTALL_DIR) find_vs_install_dir("[18.0,19.0)" VS_INSTALL_DIR) if (VS_INSTALL_DIR) message(WARNING "Visual Studio 2022 was not found; using Visual Studio 2026 instead. clang-format output may differ from pipeline expectations.") endif() endif() if (NOT VS_INSTALL_DIR) message(FATAL_ERROR "Could not determine Visual Studio installation directory.") endif() ``` -------------------------------- ### WSL Configuration Files Source: https://context7.com/microsoft/wsl/llms.txt WSL uses .wslconfig for global VM settings and wsl.conf for per-distribution settings. ```APIDOC ## [INI] WSL Configuration ### Description Configure global WSL2 VM behavior via %USERPROFILE%\.wslconfig or distribution-specific settings via /etc/wsl.conf. ### Parameters - **[wsl2]** (Section) - Global settings like memory, processors, and networking. - **[automount]** (Section) - Per-distribution mount settings for Windows drives. - **[boot]** (Section) - Systemd and startup command configuration. ### Request Example ```ini [wsl2] memory=8GB processors=4 [boot] systemd=true ``` ``` -------------------------------- ### Build WSL with CMake Build Types and Architectures Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Demonstrates various CMake commands for building the WSL project with specific configurations. This includes building for the ARM64 architecture, setting the build type to Release, and creating an MSIX bundle package. ```bash cmake . -A arm64 cmake . -DCMAKE_BUILD_TYPE=Release cmake . -DBUILD_BUNDLE=TRUE ``` -------------------------------- ### Execute Windows Binaries from Linux Source: https://context7.com/microsoft/wsl/llms.txt Interoperability commands allowing Linux shells to invoke Windows executables, pipe data between environments, and manage interop settings. ```bash notepad.exe explorer.exe . powershell.exe -Command "Get-Process | Select-Object -First 5" cat /etc/hosts | clip.exe ``` -------------------------------- ### Generate Visual Studio Solution with CMake Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Generates the Visual Studio solution file (`wsl.sln`) from the WSL source code using CMake. This is the initial step before building the project. The command `cmake .` is executed in the root directory of the cloned repository. ```bash cmake . ``` -------------------------------- ### Configure WSL Development Environment Source: https://context7.com/microsoft/wsl/llms.txt Customizing the build process via UserConfig.cmake to optimize for faster iteration, such as thinning packages and automating post-build deployment tasks. ```cmake set(WSL_DEV_BINARY_PATH "C:/wsldev") set(WSL_BUILD_THIN_PACKAGE TRUE) set(WSL_POST_BUILD_COMMAND "powershell tools/deploy/deploy-to-host.ps1") set(WSL_SKIP_APPX_SIGNING TRUE) ``` -------------------------------- ### Collect WSL logs using PowerShell Source: https://github.com/microsoft/wsl/blob/master/CONTRIBUTING.md Downloads and executes the official Microsoft WSL diagnostic script. Requires administrative privileges and outputs a log file path upon completion. ```PowerShell Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" -OutFile collect-wsl-logs.ps1 Set-ExecutionPolicy Bypass -Scope Process -Force .\collect-wsl-logs.ps1 ``` -------------------------------- ### Fetch and Make Available GSL Library Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Uses CMake's FetchContent module to download the GSL (Guidelines Support Library) from GitHub. It specifies the URL and SHA256 hash for integrity and then makes the library available for use in the build. ```cmake include(FetchContent) # Import GSL and nlohmannjson set(FETCHCONTENT_BASE_DIR ${CMAKE_BINARY_DIR}/_deps/${TARGET_PLATFORM}) FetchContent_Declare(GSL URL https://github.com/microsoft/GSL/archive/refs/tags/v4.0.0.tar.gz URL_HASH SHA256=f0e32cb10654fea91ad56bde89170d78cfbf4363ee0b01d8f097de2ba49f6ce9) FetchContent_MakeAvailable(GSL) FetchContent_GetProperties(GSL SOURCE_DIR GSL_SOURCE_DIR) ``` -------------------------------- ### Manage WSL File System Interoperability Source: https://context7.com/microsoft/wsl/llms.txt Accessing Linux files from Windows using the Plan9 protocol and mounting Windows drives within the Linux environment using drvfs. ```powershell dir \\wsl.localhost\Ubuntu\home\user copy C:\Windows\file.txt \\wsl.localhost\Ubuntu\home\user\ sudo mount -t drvfs D: /tmp/my-mount ``` -------------------------------- ### Configuring Build Targets and Assembly Info for WinUI App Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslsettings/CMakeLists.txt This code configures the build process by copying input files to their final build locations. It specifically handles the `directory.build.targets` and `Properties/AssemblyInfo.cs` files, which are essential for the build system and assembly metadata. ```cmake configure_file( "${CMAKE_CURRENT_LIST_DIR}/directory.build.targets.in" "${CMAKE_CURRENT_LIST_DIR}/directory.build.targets" ) configure_file( "${CMAKE_CURRENT_LIST_DIR}/Properties/AssemblyInfo.cs.in" "${CMAKE_CURRENT_LIST_DIR}/Properties/AssemblyInfo.cs" ) ``` -------------------------------- ### Configure CMake Project and Output Directories Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslsettings/CMakeLists.txt Sets up the C# project environment and redirects build binaries and assets to a dedicated subdirectory. This ensures cleaner packaging by isolating the wslsettings output from the main project build artifacts. ```cmake set(TargetApp wslsettings) project(${TargetApp} LANGUAGES CSharp) # needed for csharp_set_xaml_cs_properties include(CSharpUtilities) # place wsl settings binaries/assets into # separate directory to simplify packaging set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TargetApp}") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG}/${TargetApp}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE}/${TargetApp}) file(MAKE_DIRECTORY ${BIN}/${TargetApp}/Assets) ``` -------------------------------- ### Retrieve Runtime Parameters in TAEF C++ Tests Source: https://github.com/microsoft/wsl/blob/master/test/README.md Demonstrates how to access runtime parameters passed via the command line within a C++ test method using the WEX::TestExecution namespace. ```cpp using namespace WEX::Common; using namespace WEX::TestExecution; String runtimeParamString; DWORD fooBar; VERIFY_SUCCEEDED(RuntimeParameters::TryGetValue(L"foo", runtimeParamString)); VERIFY_SUCCEEDED(RuntimeParameters::TryGetValue(L"bar", fooBar)); ``` -------------------------------- ### Configure Include Directories and Link Libraries Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Sets up the necessary header search paths for the project and configures external library linking for TAEF. This ensures that the compiler can locate dependencies like WIL, GSL, and Nlohmann JSON during the build process. ```cmake include_directories(${CMAKE_CURRENT_SOURCE_DIR}/wil/include) include_directories(${WSLDEPS_SOURCE_DIR}/include) include_directories(${WIL_SOURCE_DIR}/include) include_directories(${GSL_SOURCE_DIR}/include) include_directories(${NLOHMAN_JSON_SOURCE_DIR}/include) link_directories(${TAEF_SOURCE_DIR}/build/Library/${TARGET_PLATFORM}) set(TAEF_LINK_LIBRARIES TE.Common.lib Wex.Common.lib Wex.Logger.lib) ``` -------------------------------- ### Configure WSL Init Executable and Initramfs Build Source: https://github.com/microsoft/wsl/blob/master/src/linux/init/CMakeLists.txt This CMake configuration defines the source files and dependencies for the 'init' executable. It also establishes a custom command to package the executable into an initramfs image using a PowerShell script. ```cmake set(SOURCES main.cpp binfmt.cpp config.cpp DnsServer.cpp DnsTunnelingChannel.cpp DnsTunnelingManager.cpp drvfs.cpp escape.cpp GnsEngine.cpp GnsPortTracker.cpp init.cpp localhost.cpp Localization.cpp NetworkManager.cpp plan9.cpp telemetry.cpp timezone.cpp SecCompDispatcher.cpp util.cpp WslDistributionConfig.cpp wslinfo.cpp wslpath.cpp) set(INIT_LIBRARIES ${COMMON_LINUX_LINK_LIBRARIES} netlinkutil plan9 mountutil configfile) add_linux_executable(init "${SOURCES}" "${HEADERS};${COMMON_LINUX_HEADERS}" "${INIT_LIBRARIES}") add_custom_command( OUTPUT ${INITRAMFS} "${CMAKE_CURRENT_BINARY_DIR}/CmakeFiles/initramfs" DEPENDS init ${INIT} COMMAND powershell.exe -ExecutionPolicy Bypass -NoProfile -NonInteractive -File "${CMAKE_SOURCE_DIR}/tools/create-initrd.ps1" "${INIT}" "${INITRAMFS}" COMMAND ${CMAKE_COMMAND} -E touch "${CMAKE_CURRENT_BINARY_DIR}/CmakeFiles/initramfs" VERBATIM) ``` -------------------------------- ### Set Up Automatic ClangFormat Check on Commit Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Configures the development environment to automatically check code formatting using clang-format when creating a commit. This helps maintain code style consistency throughout the development process. ```bash tools\SetupClangFormat.bat ``` -------------------------------- ### Configure Build Environment and Toolchain Paths Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Sets up the clang-format utility and defines core compiler paths for the Linux target. It uses CMake to manage file links and configuration file generation. ```cmake configure_file(${CMAKE_CURRENT_LIST_DIR}/tools/FormatSource.ps1.in ${CMAKE_BINARY_DIR}/FormatSource.ps1) cmake_path(COMPARE "${wsl_SOURCE_DIR}" EQUAL "${wsl_BINARY_DIR}" BUILD_IN_SOURCE) if (NOT ${BUILD_IN_SOURCE}) file(CREATE_LINK ${LLVM_INSTALL_DIR}/clang-format.exe ${wsl_SOURCE_DIR}/tools/clang-format.exe COPY_ON_ERROR) endif() ``` -------------------------------- ### Configure WSL Cloud Test Environment Source: https://github.com/microsoft/wsl/blob/master/cloudtest/CMakeLists.txt This script initializes the output directory and defines platform-specific test images and packages based on the target architecture. It also includes a helper function to generate test configuration files for specific image versions. ```cmake set(OUT ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/cloudtest) file(MAKE_DIRECTORY ${OUT}) if (${TARGET_PLATFORM} STREQUAL x64) set(CLOUDTEST_IMAGES "wsl-test-image-rs_prerelease-2025-01-30" "wsl-test-image-win11-23h2-ent-2024-11-18" "wsl-test-image-2022-datacenter-g2-2024-09-10" "wsl-test-image-win10-22h2-ent-g2-2024-09-10") set(CLOUDTEST_TEST_PACKAGES "Test_Packages_2025_07_28") set(DUMPTOOL_DROP "DumpTool_X64_2025-01-27") elseif (${TARGET_PLATFORM} STREQUAL arm64) set(CLOUDTEST_IMAGES) else() message(FATAL_ERROR "Unsupported target platform: ${TARGET_PLATFORM}") endif() if (OFFICIAL_BUILD) set(ALLOW_UNSIGNED_PACKAGE "0") else() set(ALLOW_UNSIGNED_PACKAGE "1") endif() function(add_test_group image version) set(DIR ${OUT}/${image}-wsl${version}) file(MAKE_DIRECTORY ${DIR}) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/TestMap.xml.in ${DIR}/TestMap.xml) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/TestGroup.xml.in ${DIR}/TestGroup.xml) endfunction() foreach(image ${CLOUDTEST_IMAGES}) add_test_group("${image}" "1") add_test_group("${image}" "2") endforeach() ``` -------------------------------- ### Configure Per-Distribution Settings (wsl.conf) Source: https://context7.com/microsoft/wsl/llms.txt This INI file configures settings specific to a WSL distribution, located at `/etc/wsl.conf` within the Linux environment. It controls automatic mounting of Windows drives, network settings like hostname and DNS resolution, Windows interoperability, the default user, and systemd support. ```ini # /etc/wsl.conf - Per-distribution settings (inside Linux) [automount] # Auto-mount Windows drives under /mnt enabled=true root=/mnt/ options="metadata,umask=22,fmask=11" mountFsTab=true [network] # Network configuration generateHosts=true generateResolvConf=true hostname=my-wsl-host [interop] # Windows interoperability enabled=true appendWindowsPath=true [user] # Default user when launching WSL default=myuser [boot] # Systemd support (WSL 0.67.6+) systemd=true # Custom boot command command=/usr/local/bin/startup.sh ``` -------------------------------- ### Fetch and Make Available nlohmannjson Library Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Fetches the nlohmannjson library using FetchContent, specifying the download URL and SHA256 hash. This ensures the JSON library is downloaded and available for the project. ```cmake FetchContent_Declare(nlohmannjson URL https://github.com/nlohmann/json/releases/download/v3.12.0/json.tar.xz URL_HASH SHA256=42f6e95cad6ec532fd372391373363b62a14af6d771056dbfc86160e6dfff7aa ) FetchContent_MakeAvailable(nlohmannjson) FetchContent_GetProperties(nlohmannjson SOURCE_DIR NLOHMAN_JSON_SOURCE_DIR) ``` -------------------------------- ### Define Executable Sources and Headers (CMake) Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslrelay/CMakeLists.txt This snippet defines the source and header files for the 'wslrelay' executable using CMake's set command. It lists the .cpp and .rc files as sources and .h files as headers. ```cmake set(SOURCES localhost.cpp main.cpp main.rc) set(HEADERS localhost.h resource.h) ``` -------------------------------- ### Setting Package References for WinUI Template Studio Sample App Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslsettings/CMakeLists.txt This snippet sets the Visual Studio package references for the target application. It includes various Community Toolkit packages, .NET extension hosting, Windows App SDK, XAML Behaviors, and WinUIEx. The versions are dynamically set using variables like CTK_MVVM_VERSION. ```cmake set_property( TARGET ${TargetApp} PROPERTY VS_PACKAGE_REFERENCES "CommunityToolkit.Mvvm_${CTK_MVVM_VERSION};\nCommunityToolkit.WinUI.Animations_${CTK_ANIMATIONS_VERSION};\nCommunityToolkit.WinUI.Controls.SettingsControls_${CTK_STTNGS_CTRLS_VERSION};\nMicrosoft.Extensions.Hosting_${EXTS_HOSTING_VERSION};\nMicrosoft.WindowsAppSDK_${WIN_APP_SDK_VERSION};\nMicrosoft.Xaml.Behaviors.WinUI.Managed_${XAML_BEHAVIORS_VERSION};\nWinUIEx_${WINUIEX_VERSION}" ) ``` -------------------------------- ### wslapi.dll Public API Source: https://context7.com/microsoft/wsl/llms.txt The wslapi.dll provides functions for third-party applications to register, configure, and interact with WSL distributions. ```APIDOC ## [C++] wslapi.dll Operations ### Description Functions to manage WSL distribution lifecycle, including registration, configuration, and process execution. ### Method N/A (Native C++ API) ### Parameters - **distributionName** (LPCWSTR) - Required - The name of the WSL distribution. ### Response - **HRESULT** - Returns S_OK on success, or an error code on failure. ### Request Example ```cpp // Check if a distribution is registered BOOL isRegistered = WslIsDistributionRegistered(L"Ubuntu"); // Launch a process HRESULT hr = WslLaunch(L"Ubuntu", L"ls -la", FALSE, hIn, hOut, hErr, &exitCode); ``` ``` -------------------------------- ### Configure Global WSL2 Settings (.wslconfig) Source: https://context7.com/microsoft/wsl/llms.txt This INI file defines global settings for the WSL2 virtual machine, including memory and CPU limits, swap configuration, kernel path, networking options, GPU support, and experimental features. It is located at `%USERPROFILE%\.wslconfig`. ```ini # %USERPROFILE%\.wslconfig - Global WSL2 VM settings [wsl2] # Memory and CPU limits memory=8GB processors=4 swap=4GB swapFile=C:\\temp\\wsl-swap.vhdx # Kernel and networking kernel=C:\\Users\\user\\custom-kernel kernelCommandLine=vsyscall=emulate # Nested virtualization (for Docker, etc.) nestedVirtualization=true # Network configuration networkingMode=mirrored dnsTunneling=true firewall=true autoProxy=true # GPU support gpuSupport=true # Memory reclaim settings autoMemoryReclaim=gradual pageReporting=true # Sparse VHD (reclaim disk space automatically) sparseVhd=true [experimental] # Experimental features autoMemoryReclaim=dropcache sparseVhd=true ``` -------------------------------- ### Configure WSL Build Environment and Versioning Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Sets up the build configuration types, validates the project versioning against regex patterns, and enforces specific versioning rules for official builds. ```cmake set(CMAKE_CONFIGURATION_TYPES "${CMAKE_BUILD_TYPE}" CACHE STRING "" FORCE) find_commit_hash(COMMIT_HASH) if (NOT PACKAGE_VERSION) find_version(PACKAGE_VERSION WSL_NUGET_PACKAGE_VERSION) endif () if (NOT PACKAGE_VERSION MATCHES "^([0-9]+).([0-9]+).([0-9]+).([0-9]+)$") message(FATAL_ERROR "PACKAGE_VERSION is invalid: '${PACKAGE_VERSION}'.") endif() ``` -------------------------------- ### Collect WSL process crash dumps Source: https://github.com/microsoft/wsl/blob/master/CONTRIBUTING.md Uses the diagnostic script with the -Dump flag to capture user-mode crash dumps for all running WSL processes. Requires administrative privileges. ```PowerShell Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" -OutFile collect-wsl-logs.ps1 Set-ExecutionPolicy Bypass -Scope Process -Force .\collect-wsl-logs.ps1 -Dump ``` -------------------------------- ### Format WSL Source Code with ClangFormat Source: https://github.com/microsoft/wsl/blob/master/doc/docs/dev-loop.md Ensures code consistency by formatting the WSL source code using clang-format. This command is necessary for pull requests to be merged. It provides options for formatting all files or only modified files. ```powershell powershell .\FormatSource.ps1 -ModifiedOnly $false ``` -------------------------------- ### Create Executable and Add Dependencies (CMake) Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslrelay/CMakeLists.txt This CMake snippet creates the 'wslrelay' executable from the defined sources and headers. It also establishes a dependency on the 'common' target, ensuring 'common' is built before 'wslrelay'. ```cmake add_executable(wslrelay WIN32 ${SOURCES} ${HEADERS}) add_dependencies(wslrelay common) ``` -------------------------------- ### Collect WSL Diagnostic Logs (PowerShell) Source: https://context7.com/microsoft/wsl/llms.txt This PowerShell script, `collect-wsl-logs.ps1`, gathers comprehensive diagnostic information for troubleshooting WSL issues. It can be run with various parameters to focus on specific areas like storage or networking, enable process dumps, or use custom tracing profiles. The script needs to be downloaded and executed, potentially requiring administrator privileges. ```powershell # Download and run the log collection script (run as Administrator) Invoke-WebRequest -UseBasicParsing ` "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" ` -OutFile collect-wsl-logs.ps1 Set-ExecutionPolicy Bypass -Scope Process -Force # Basic log collection .\collect-wsl-logs.ps1 # Output: Logs saved in: C:\Users\...\WslLogs-2024-01-15_10-30-45.zip # Storage-specific tracing (for disk/VHD issues) .\collect-wsl-logs.ps1 -LogProfile storage # Networking-specific tracing (includes packet capture, tcpdump) .\collect-wsl-logs.ps1 -LogProfile networking # Networking with WSL restart (captures network creation logs) .\collect-wsl-logs.ps1 -LogProfile networking -RestartWslReproMode # HvSocket-specific tracing .\collect-wsl-logs.ps1 -LogProfile hvsocket # Collect process dumps for crash analysis .\collect-wsl-logs.ps1 -Dump # Use a custom WPRP profile file .\collect-wsl-logs.ps1 -LogProfile C:\custom\my-profile.wprp # The script collects: ``` -------------------------------- ### Manage Output Directories and Packaging Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt Configures runtime output directories and creates symbolic links for necessary DLL dependencies. It also handles the generation of development certificates for package signing. ```cmake set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/${TARGET_PLATFORM}) file(CREATE_LINK ${WSL_DEVICE_HOST_SOURCE_DIR}/bin/${TARGET_PLATFORM}/wsldevicehost.dll ${BIN}/wsldevicehost.dll) if (NOT EXISTS ${PACKAGE_CERTIFICATE}) execute_process(COMMAND powershell.exe -ExecutionPolicy Bypass -NoProfile -NonInteractive ${CMAKE_CURRENT_LIST_DIR}/tools/create-dev-cert.ps1 -OutputPath ${PACKAGE_CERTIFICATE}) endif() ``` -------------------------------- ### Find NuGet Packages for WSL Components Source: https://github.com/microsoft/wsl/blob/master/CMakeLists.txt This section of the CMake script finds and downloads various NuGet packages required for WSL functionality. It includes packages for Direct3D, MSAL, MSRDC, TAEF, WIL, DeviceHost, Kernel, and more, with some being architecture-specific. ```cmake # Download nuget packages restore_nuget_packages() # Load nuget packages versions and paths parse_nuget_packages_versions() find_nuget_package(Microsoft.Direct3D.Linux DIRECT3D /build/native) find_nuget_package(Microsoft.Identity.MSAL.WSL.Proxy MSAL /build/native/bin) find_nuget_package(Microsoft.RemoteDesktop.Client.MSRDC.SessionHost MSRDC /build/native/bin) find_nuget_package(Microsoft.Taef TAEF /) find_nuget_package(Microsoft.Windows.ImplementationLibrary WIL /) find_nuget_package(Microsoft.WSL.DeviceHost WSL_DEVICE_HOST /build/native) find_nuget_package(Microsoft.WSL.Kernel KERNEL /build/native) find_nuget_package(Microsoft.WSL.bsdtar BSDTARD /build/native/bin) find_nuget_package(Microsoft.WSL.LinuxSdk LINUXSDK /) find_nuget_package(Microsoft.WSL.TestDistro TEST_DISTRO /) find_nuget_package(Microsoft.WSLg WSLG /build/native/bin) find_nuget_package(vswhere VSWHERE /tools) find_nuget_package(Wix WIX /tools/net6.0/any) # Architecture-specific nuget packages from the OS repo. if (${TARGET_PLATFORM} STREQUAL "x64") find_nuget_package(Microsoft.DXCore.Linux.amd64fre DXCORE /build/native) find_nuget_package(Microsoft.WSL.Dependencies.amd64fre WSLDEPS /build/native) endif() if (${TARGET_PLATFORM} STREQUAL "arm64") find_nuget_package(Microsoft.DXCore.Linux.arm64fre DXCORE /build/native) find_nuget_package(Microsoft.WSL.Dependencies.arm64fre WSLDEPS /build/native) endif() # Wsl Settings packages find_nuget_package(CommunityToolkit.Mvvm CTK_MVVM /) find_nuget_package(CommunityToolkit.WinUI.Animations CTK_ANIMATIONS /) find_nuget_package(CommunityToolkit.WinUI.Controls.SettingsControls CTK_STTNGS_CTRLS /) find_nuget_package(Microsoft.Extensions.Hosting EXTS_HOSTING /) find_nuget_package(Microsoft.NETCore.App.Runtime.win-${TARGET_PLATFORM} DOTNET_RUNTIME /) find_nuget_package(Microsoft.WindowsAppSDK WIN_APP_SDK /) find_nuget_package(Microsoft.Windows.SDK.NET.Ref WINDOWS_SDK_DOTNET /) find_nuget_package(Microsoft.Xaml.Behaviors.WinUI.Managed XAML_BEHAVIORS /) find_nuget_package(WinUIEx WINUIEX /) ``` -------------------------------- ### Configuring Target Platform Versions for WinUI App Source: https://github.com/microsoft/wsl/blob/master/src/windows/wslsettings/CMakeLists.txt This section defines the target and minimum platform versions for the Windows application. It sets both the raw version numbers and the formatted 'windowsX.Y.Z.W' strings required for Windows SDK compatibility. ```cmake set( TARGET_PLATFORM_VERSION "10.0.26100.0" ) set( WINDOWS_TARGET_PLATFORM_VERSION "windows${TARGET_PLATFORM_VERSION}" ) set( TARGET_PLATFORM_MIN_VERSION "10.0.19041.0" ) set( WINDOWS_TARGET_PLATFORM_MIN_VERSION "windows${TARGET_PLATFORM_MIN_VERSION}" ) ```