Copilot instructions
.github/copilot-instructions.mdCopilot instructions
Quality
88/100
Scores the file, not the repository.Length
2,208 words
63 headings · 11 code blocksRepository
33k
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.1# Windows Subsystem for Linux (WSL)23**ALWAYS reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the info here.**45WSL is the Windows Subsystem for Linux - a compatibility layer for running Linux binary executables natively on Windows. This repository contains the core Windows components that enable WSL functionality.67## Coding Conventions89### Naming1011- **Classes/Structs**: `PascalCase` (e.g., `ConsoleProgressBar`, `DeviceHostProxy`)12- **Functions/Methods**: `PascalCase()` (e.g., `GetFamilyName()`, `MultiByteToWide()`)13- **Member variables**: `m_camelCase` (e.g., `m_isOutputConsole`, `m_outputHandle`)14- **Local variables**: `camelCase` (e.g., `distroGuidString`, `asyncResponse`)15- **Constants**: `c_camelCase` with `constexpr` (e.g., `constexpr size_t c_progressBarWidth = 58;`)16- **Namespaces**: lowercase with `::` nesting (e.g., `wsl::windows::common::registry`)17- **Enums**: `PascalCaseValue` (e.g., `LxssDistributionStateInstalled`)18- **Windows types**: Keep as-is (`LPCWSTR`, `HRESULT`, `DWORD`, `ULONG`, `GUID`)1920### Error Handling2122Use WIL (Windows Implementation Libraries) macros — **never** bare `if (FAILED(hr))`:23- `THROW_IF_FAILED(hr)` — throw on HRESULT failure24- `THROW_HR_IF(hr, condition)` — conditional throw25- `THROW_HR_IF_MSG(hr, condition, fmt, ...)` — conditional throw with message26- `THROW_IF_NULL_ALLOC(ptr)` — throw on null allocation27- `THROW_LAST_ERROR_IF(condition)` — throw last Win32 error28- `RETURN_IF_FAILED(hr)` — return HRESULT on failure (no throw)29- `RETURN_LAST_ERROR_IF_EXPECTED(condition)` — expected failure path30- `LOG_IF_FAILED(hr)` — log but don't throw31- `CATCH_LOG()` — catch and log exceptions3233For user-facing errors, set a localized message before throwing:34```cpp35THROW_HR_WITH_USER_ERROR(E_INVALIDARG, Localization::MessageConfigInvalidBoolean(name, value));36```3738At API boundaries (COM interfaces), return `HRESULT` with out params. Internal code throws exceptions.3940### Memory Management and RAII4142Use WIL smart pointers — **never** raw `CloseHandle()` or manual cleanup:43- `wil::unique_handle` — kernel handles44- `wil::com_ptr<T>` — COM objects45- `wil::unique_hfile` — file handles46- `wil::unique_hkey` — registry keys47- `wil::unique_event` — events48- `wil::unique_hlocal_string` — HLOCAL strings49- `wil::unique_cotaskmem_string` — CoTaskMem strings5051For non-standard resource types, use `wil::unique_any<Type, Deleter, Fn>`.5253For cleanup scopes, use `wil::scope_exit`:54```cpp55auto cleanup = wil::scope_exit([&] { registry::DeleteKey(LxssKey, guid.c_str()); });56// ... work ...57cleanup.release(); // dismiss on success58```5960### Synchronization6162Use `wil::srwlock` (Slim Reader/Writer locks) with SAL annotations:63```cpp64mutable wil::srwlock m_lock;65_Guarded_by_(m_lock) std::vector<Entry> m_entries;66```6768### Strings6970- `std::wstring` / `std::wstring_view` are dominant throughout the codebase71- Use `MultiByteToWide()` / `WideToMultiByte()` from `stringshared.h` for conversions72- Use `std::format()` for formatting (the repo defines `std::formatter<std::wstring, char>` for wide-to-narrow support)73- The `STRING_TO_WIDE_STRING()` macro handles compile-time conversion7475### Copy/Move Semantics7677Use macros from `defs.h` to declare copy/move behavior:78```cpp79NON_COPYABLE(MyClass);80NON_MOVABLE(MyClass);81DEFAULT_MOVABLE(MyClass);82```8384### Headers8586- Use `#pragma once` (no traditional `#ifndef` include guards)87- In Windows C++ components, every `.cpp` file must start with `#include "precomp.h"`88- Linux-side code (`src/linux/`) does not use precompiled headers89- Use `.h` for C-compatible headers, `.hpp` for C++-only headers90- Include order is enforced by `.clang-format` (precomp first, then system, then project)9192### Copyright Headers9394Use this single-line format for new files:95```cpp96// Copyright (C) Microsoft Corporation. All rights reserved.97```9899Some older files use the block format (`/*++ Copyright (c) Microsoft. All rights reserved. ... --*/`). Match the surrounding files in the same directory when editing.100101### Localization102103- Use `wsl::shared::Localization::MessageXxx()` static methods for user-facing strings104- Use `EMIT_USER_WARNING(Localization::MessageXxx(...))` for non-fatal config warnings105- All new user-facing strings must have entries in `localization/strings/en-US/Resources.resw`106- In Resources.resw comments, use `{Locked="..."}` to prevent translation of `.wslconfig` property key names107- Localized files are generated by a separate localization team and regenerated downstream, so translation edits in a GitHub PR cannot be merged (they would be overwritten). This covers the per-locale `localization/strings/<locale>/Resources.resw` UI strings and the per-locale `intune/<locale>/WSL.adml` policy templates (anything other than the `en-US` sources and the neutral `intune/WSL.admx`). Filing a GitHub issue is the correct path for contributors; see `CONTRIBUTING.md`. Ignore this guidance for automated localization-service PRs that are generated by that pipeline.108- Community localization reports come in as **both GitHub issues and pull requests** - when triaging, look for both and file a tracking Bug for each. These are tracked via Bugs in the GCS Azure DevOps project, not merged directly. See `.github/copilot/localization-bugs.md` for the project coordinates, required fields, and `az boards` workflow.109110### Telemetry and Logging111112- `WSL_LOG(Name, ...)` — standard trace event113- `WSL_LOG_DEBUG(Name, ...)` — debug-only (compiled out in release via `if constexpr`)114- `WSL_LOG_TELEMETRY(Name, Tag, ...)` — metrics with privacy tag and version info115- Provider: `g_hTraceLoggingProvider`, initialized via `WslTraceLoggingInitialize()`116117### Platform Conditionals118119Prefer `constexpr` checks over `#ifdef` where possible:120```cpp121if constexpr (wsl::shared::Debug) { /* debug-only code */ }122if constexpr (wsl::shared::Arm64) { /* ARM64-specific code */ }123```124125For compiler-specific code, use `#ifdef _MSC_VER` (Windows) / `#ifdef __GNUC__` (Linux).126127### Formatting128129Enforced by `.clang-format`:130- 130 character column limit131- 4-space indentation, no tabs132- Allman-style braces (opening brace on new line for classes, functions, structs, control statements)133- Left-aligned pointers (`int* ptr`, not `int *ptr`)134- `InsertBraces: true` — all control statements must have braces135136### IDL / COM Conventions137138When modifying service interfaces (`src/windows/service/inc/`):139- Interface attributes on separate lines: `[uuid(...), pointer_default(unique), object]`140- String params: `[in, unique] LPCWSTR` with `[string]` for marshaled strings141- Handle params: `[in, system_handle(sh_file)] HANDLE`142- User-facing errors: pass `[in, out] LXSS_ERROR_INFO* Error`143- **ABI stability applies only to SDK-facing and public surfaces.** `WSLCCompat.idl` (the WSLC SDK-facing layer) and the public plugin API (`WslPluginApi.h`) must stay backward compatible: do not add, remove, or reorder methods on their existing interfaces, and do not change struct layouts. Introduce a new versioned interface with a new IID instead. Every other interface (`IWSLCSession` in `wslc.idl`, the interfaces in `wslservice.idl`, etc.) is internal and non-stable: rebuilt and shipped in lockstep with its only clients, so appending new methods to those is fine.144- Custom error codes: `WSL_E_xxx` via `MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, WSL_E_BASE + N)`145146### Config File (.wslconfig) Conventions147148When adding settings to `src/shared/configfile/`:149- Format is `.gitconfig`-style INI: `[section]`, `key = value`, `#` comments, `\` line continuation150- Use the `ConfigKey` template class for type-safe parsing151- Supported types: `bool`, `int` (hex/octal), `std::string`, `std::wstring`, `MemoryString`, `MacAddress`, enum maps152- Report invalid values with `EMIT_USER_WARNING(Localization::MessageConfigXxx(...))`153- New settings require a corresponding localization string in Resources.resw154155## Repository Navigation156157### Key Directories158- `src/windows/` — Main Windows WSL service components159- `src/linux/` — Linux-side WSL components160- `src/shared/` — Shared code between Windows and Linux161- `test/windows/` — Windows-based tests (TAEF framework)162- `test/linux/unit_tests/` — Linux unit test suite163- `doc/` — Documentation source (MkDocs)164- `tools/` — Build and deployment scripts165- `distributions/` — Distribution validation and metadata166- `localization/` — Localized string resources167168### Namespace → Directory Map169170| Namespace | Location |171|---|---|172| `wsl::shared::` | `src/shared/` |173| `wsl::windows::common::` | `src/windows/common/` |174| `wsl::windows::service::` | `src/windows/service/exe/` |175| `wsl::core::` | `src/windows/service/exe/` |176| `wsl::core::networking::` | `src/windows/common/` + `src/windows/service/exe/` |177| `wsl::linux::` | `src/linux/init/` |178179### Key Files180- `src/shared/inc/defs.h` — Shared platform definitions (NON_COPYABLE, Debug, Arm64, etc.)181- `src/shared/inc/stringshared.h` — String conversion utilities182- `src/windows/common/WslTelemetry.h` — Telemetry macros183- `src/windows/common/ExecutionContext.h` — Error context and user-facing error macros184- `src/windows/service/inc/wslservice.idl` — Main service COM interface definitions185- `src/windows/service/inc/wslc.idl` — Container COM interface definitions186- `src/windows/inc/WslPluginApi.h` — Plugin API header187- `src/shared/configfile/configfile.h` — Config file parser188- `.clang-format` — Code formatting rules (130 col, 4-space indent, Allman braces)189190## Building and Deploying191192### Critical Platform Requirements193- **Full builds ONLY work on Windows** with Visual Studio and Windows SDK 26100194- **DO NOT attempt to build the main WSL components on Linux** — they require Windows-specific APIs, MSBuild, and Visual Studio toolchain195- Many validation and development tasks CAN be performed on Linux (documentation, formatting, Python validation scripts)196197### Windows Build Requirements198- CMake >= 3.25 (`winget install Kitware.CMake`)199- Visual Studio with these components:200 - Windows SDK 26100201 - MSBuild202 - Universal Windows platform support for v143 build tools (X64 and ARM64)203 - MSVC v143 - VS 2022 C++ ARM64 build tools (Latest + Spectre) (X64 and ARM64)204 - C++ core features205 - C++ ATL for latest v143 tools (X64 and ARM64)206 - C++ Clang compiler for Windows207 - .NET desktop development208 - .NET WinUI app development tools209- Enable Developer Mode in Windows Settings OR run with Administrator privileges (required for symbolic link support)210211### Building WSL (Windows Only)2121. Clone the repository2132. Generate Visual Studio solution: `cmake .`2143. Build: `cmake --build . -- -m` OR open `wsl.sln` in Visual Studio215216Build parameters:217- `cmake . -A arm64` — Build for ARM64218- `cmake . -DCMAKE_BUILD_TYPE=Release` — Release build219- `cmake . -DBUILD_BUNDLE=TRUE` — Build bundle MSIX package (requires ARM64 built first)220221### Deploying WSL (Windows Only)222- Install MSI: `bin\<platform>\<target>\wsl.msi`223- OR use script: `powershell tools\deploy\deploy-to-host.ps1`224- For Hyper-V VM: `powershell tools\deploy\deploy-to-vm.ps1 -VmName <vm> -Username <user> -Password <pass>`225226## Testing227228### Writing Tests (TAEF Framework)229230Tests use TAEF. See `.github/copilot/test.md` for detailed patterns and macros.231232Key points:233- Use `WSL_TEST_CLASS(Name)` — not raw `BEGIN_TEST_CLASS`234- Use `VERIFY_*` macros for assertions (`VERIFY_ARE_EQUAL`, `VERIFY_IS_TRUE`, etc.)235- Skip macros: `WSL1_TEST_ONLY()`, `WSL2_TEST_ONLY()`, `SKIP_TEST_ARM64()`236- Test infrastructure is in `test/windows/Common.h`237238### Running Tests (Windows Only)239240**CRITICAL: ALWAYS build the ENTIRE project before running tests:**241```powershell242cmake --build . -- -m243bin\<platform>\<target>\test.bat244```245246**Why full build is required:**247- Tests depend on multiple components (libwsl.dll, wsltests.dll, wslservice.exe, etc.)248- Partial builds will cause test failures249- **DO NOT skip the full build step even if only one file changed**250251Test execution:252- Run all tests: `bin\<platform>\<target>\test.bat`253- Run subset: `bin\<platform>\<target>\test.bat /name:*UnitTest*`254- Run specific test: `bin\<platform>\<target>\test.bat /name:<class>::<test>`255- WSL1 tests: Add `-Version 1` flag256- Fast mode (after first run): Add `-f` flag (requires `wsl --set-default test_distro`)257- **Requires Administrator privileges**258259Test debugging:260- Attach WinDbgX automatically: `/attachdebugger`261- Wait for debugger (manual attach): `/waitfordebugger`262- Break on failure: `/breakonfailure`263- Run in-process: `/inproc`264265### Linux Unit Tests (Linux Only)266- Location: `test/linux/unit_tests/`267- Build script: `test/linux/unit_tests/build_tests.sh`268- **Note**: Requires specific Linux build environment setup not covered in main build process269270## Cross-Platform Validation Tasks271272### Documentation (Works on Linux/Windows)273- Install tools: `pip install mkdocs-mermaid2-plugin mkdocs --break-system-packages`274- Build docs: `mkdocs build -f doc/mkdocs.yml`275- Output location: `doc/site/`276- **Note**: May show warnings about mermaid CDN access on restricted networks277278### Code Formatting and Validation279- Format all source (Windows, requires `cmake .` first): `.\FormatSource.ps1`280- Format check (Linux/cross-platform): `clang-format --dry-run --style=file <files>`281- Validate copyright headers: `python3 tools/devops/validate-copyright-headers.py`282 - **Note**: Will report missing headers in generated/dependency files (`_deps/`), which is expected283- Validate localization: `python3 tools/devops/validate-localization.py`284 - **Note**: Only works after Windows build (requires `localization/strings/en-US/Resources.resw`)285286### Distribution Validation (Limited on Linux)287- Validate distribution info: `python3 distributions/validate.py distributions/DistributionInfo.json`288- **Note**: May fail on Linux due to network restrictions accessing distribution URLs289290### Pre-commit Checklist291Always run before committing:2921. `.\FormatSource.ps1` to verify formatting on changed C++ files2932. `python3 tools/devops/validate-copyright-headers.py` (ignore `_deps/` warnings)2943. `mkdocs build -f doc/mkdocs.yml` if documentation changed2954. Full Windows build if core components changed296297**Note**: The `.gitignore` properly excludes build artifacts (`*.sln`, `*.dll`, `*.pdb`, `obj/`, `bin/`, etc.) — do not commit these files.298299## Frequently Used Commands300301### Windows Development302```powershell303# Initial setup304cmake .305cmake --build . -- -m306307# Deploy and test308powershell tools\deploy\deploy-to-host.ps1309wsl --version310311# Run tests312bin\x64\debug\test.bat313```314315### Cross-Platform Validation316```powershell317# Documentation318mkdocs build -f doc/mkdocs.yml319320# Code formatting (Windows)321.\FormatSource.ps1322323# Copyright header validation (reports expected issues in _deps/)324python3 tools/devops/validate-copyright-headers.py325326# Distribution validation (may fail on networks without external access)327python3 distributions/validate.py distributions/DistributionInfo.json328```329330## Debugging and Logging331332### ETL Tracing (Windows Only)333```powershell334# Collect traces335wpr -start diagnostics\wsl.wprp -filemode336# [reproduce issue]337wpr -stop logs.ETL338339# Available profiles:340# - WSL (default) - General WSL tracing341# - WSL-Storage - Enhanced storage tracing342# - WSL-Networking - Comprehensive networking tracing343# - WSL-HvSocket - HvSocket-specific tracing344# Example: wpr -start diagnostics\wsl.wprp!WSL -filemode345```346347### Log Analysis Tools348- Use WPA (Windows Performance Analyzer) for ETL traces349- Key providers: `Microsoft.Windows.Lxss.Manager`, `Microsoft.Windows.Subsystem.Lxss`350- For graphical/audio (WSLg) issues, see `.github/copilot/wslg-logs.md`. `collect-wsl-logs.ps1` gathers WSLg logs (`/mnt/wslg`: weston.log, pulseaudio.log, wlog.log, stderr.log, versions.txt) into a `wslg/` folder using `wsl.exe --system --user root`; crash dumps (`%TEMP%\wsl-crashes`, legacy `/mnt/wslg/dumps`) are only collected with `-Dump`. WSLg code lives in https://github.com/microsoft/wslg, not this repo.351352### Debug Console (Linux)353Add to `%USERPROFILE%\.wslconfig`:354```ini355[wsl2]356debugConsole=true357```358359### Common Debugging Commands360- Debug shell: `wsl --debug-shell`361- Collect WSL logs: `powershell diagnostics\collect-wsl-logs.ps1`362- Network logs: `powershell diagnostics\collect-wsl-logs.ps1 -LogProfile networking`363364## Timing and Timeout Guidelines365366**NEVER CANCEL these operations — always wait for completion:**367368| Operation | Typical Duration | Minimum Timeout |369|---|---|---|370| Full Windows build | 20-45 minutes | 60+ minutes |371| Full test suite | 30-60 minutes | 90+ minutes |372| Unit test subset | 5-15 minutes | 30+ minutes |373| Documentation build | ~0.5 seconds | 5+ minutes |374| Distribution validation | 2-5 minutes | 15+ minutes |375376## CI/CD Integration377378### GitHub Actions379- **distributions.yml** — Validates distribution metadata (Linux)380- **documentation.yml** — Builds and deploys docs (Linux)381- **modern-distributions.yml** — Tests modern distribution support382383## Development Environment Setup384385### Windows (Full Development)3861. Install Visual Studio with required components (listed above)3872. Install CMake 3.25+3883. Enable Developer Mode3894. Clone repository3905. Run `cmake .` to generate solution391392### Linux (Documentation/Validation Only)3931. Install Python 3.8+3942. Install docs tools: `pip install mkdocs-mermaid2-plugin mkdocs`3953. Clone repository3964. Run validation commands as needed397398Remember: **This is a Windows-focused project**. While some tasks can be performed on Linux, full WSL development requires Windows with Visual Studio.
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| pytorch/pytorch.github/copilot-instructions.md · 102k | Copilot instructions | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| dotnet/roslyn.github/instructions/Compiler.instructions.md · 21k | Copilot instructions | buildteststylearch+3 | 99/100 | 3 days ago | |
| dotnet/roslyn.github/copilot-instructions.md · 21k | Copilot instructions | buildteststylearch+3 | 97/100 | 3 days ago | |
| ardalis/CleanArchitecture.github/copilot-instructions.md · 18k | Copilot instructions | buildteststylearch+4 | 96/100 | 3 days ago | |
| dotnet/maui.github/instructions/templates.instructions.md · 23k | Copilot instructions | buildteststylearch+1 | 92/100 | 3 days ago | |
| dotnet/maui.github/instructions/integration-tests.instructions.md · 23k | Copilot instructions | setupteststyledo-not | 92/100 | 3 days ago | |
| tesseract-ocr/tesseract.github/copilot-instructions.md · 76k | Copilot instructions | setupbuildtestlint-format+5 | 89/100 | 3 days ago | |
| PowerShell/PowerShell.github/instructions/start-native-execution.instructions.md · 55k | Copilot instructions | buildstylearchgit+1 | 86/100 | 3 days ago |
