Как собрать ядро linux на windows

But huh? What do you mean by compiling your own Linux Kernel for Windows!? Well little friends, if you haven’t been in a cave in the last few months you’ve certainly heard that Microsoft will now distribute a Linux Kernel along with Windows.

Windows Subsystem for Linux 2 (WSL2), the WSL 1 updated, Microsoft’s “Wine” (for those who don’t know Wine is the project that tries to run windows applications on Linux 😝), now runs on top of a real Linux Kernel and gives you the possibility to load a customized Kernel inside Windows.

WSL and WSL 2 – Differences

WSL (Windows Subsystem for Linux) is a Microsoft project to natively run Linux applications, Linux distros on Windows without a virtual machine. The idea is, roughly speaking, to “translate” Linux syscalls into Windows syscalls. In other words, the application will use the native Windows NT kernel to run.

WSL works very well, we can run distros and Linux user space applications like Ubuntu and Debian with this technology. The problem here is the big work that the WSL team has to do this “translation” and support all the functionality between the systems, still making sure that it will behave as expected, not to mention that the Linux Kernel is almost like a living organism that is in active development and it is difficult for the WSL team to keep up with the latest updates.

To solve this, and other problems, WSL 2 was proposed. The main idea is the same, running Linux applications, Linux distros on Windows. But now running natively on top of a virtualized Linux Kernel on a very lightweight utility Hyper-V VM. The Linux Kernel is open source, why spend time “translating” syscall if I can use it directly to run my applications?

So Microsoft compiles a tuned Linux kernel, customized and optimized to run on top of its Hyper-V with a very good performance, better than that delivered by the normal WSL.

Too bad the Wine folks don’t have the windows NT Kernel code to do the same … 🤔

Compiling your own Linux kernel for WSL 2

*The following steps were performed on Windows 189 build 18980.1, which you can download by participating in Windows Insiders.

WSL 2 not only loads a native Linux Kernel, the image of the Linux Kernel is in the directory C:\WINDOWS\System32\lxss\tools\kernelbut it also gives us the option of loading a customized Linux kernel. That’s right, we can compile and customize our own kernel to be loaded into WSL 2.

Standard Version – Longterm

The standard version that is delivered with build 18980.1 is the 4.19.67:

Microsoft, which is not silly, is using the latest longterm version of the Linux Kernel, v4.19. The source code for the Kernel used with WSL 2 is on Microsoft’s GitHub in the following repository: https://github.com/microsoft/WSL2-Linux-Kernel.

The code in this repository has some modifications, and tricks, to make the Kernel work optimally for Hyper-V. Checking the Makefile of this repository we can see that the team is already working with version 4.19.72, but longterm has already received updates and is at version 4.19.74.

So let’s not wait for Microsoft to send a Kernel update, we will compile it ourselves! (for fun, of course 😎)

Compiling your Kernel

Not only will we compile our custom kernel for WSL 2, but we will do it using WSL 2 itself 🤯. For this I merge directly from the Linux git tree stable with the WSL2-Linux-Kernel git tree that resulted in this branch: https://github.com/microhobby/linus-tree/tree/wsl_4.19.74

For compilation I am using the Debian distro and we will need the following packages:

With the dependencies installed we will clone the merge:

Before starting the game, let’s make a small change. In the standard Microsoft config, on line 22 we have the “LOCALVERSION” config:

This config adds a name to the release version of the compiled Kernel:

I will modify this config to the following:

All set, let’s compile our kernel with the following command:

This compilation should take about 10 minutes or more. Don’t forget to pass the “-j” argument at the end of the command, with the number of CPU cores that your machine has, so that the compilation takes place in parallel and speeds up the process a lot.

If all goes well at the end of the build we will have something like this:

Loading your own Kernel on WSL 2

With the Kernel compiled we will have the following file in the source root:

This file is the “image”, raw binary of the Linux kernel and has the entire kernel and drivers built in. Let’s copy it to your user’s default windows folder:

Remember to change the <seuUser> to the name of your Windows user.

Now on Windows create a file called .wslconfig, also inside your user’s folder with the following content:

This file is the tricks of the trade. The WSL checks in it the kernel property which is the absolute path to the custom Kernel image that we want to load in Hyper-V, to use in conjunction with WSL 2. Again, remember to change the <seuUser> to the name of your Windows user. And it is important that this file is in the root of your user’s folder!

Now we’re almost there. To load the new Kernel we have to first turn off the distro that is running, and just close the window, or tab of the new terminal, does not solve. We have to open powershell and do the following:

Here I am sending “Debian” as an argument because it is the distro I am using, if you are using another distro modify this argument.

Now is the moment of truth. Open the Linux distro, if everything goes as expected, WSL 2 will see that we have a .wslconfig file in our user folder with a new Kernel, it will load the image we passed in Hyper-V and it will run our customized Kernel:

Done, now we are running the latest version, “MicroHobby”, stable longterm of the Linux Kernel on Windows through WSL 2.

Conclussions

This is a really cool extension feature in WSL 2 that adds a lot of possibilities to the developer. Being able to configure our own Kernel we are no longer stuck only with the modules and configs that are in the image of Microsoft’s standard Linux Kernel.

Youtube

Even if you prefer, I showed in practice the subject covered in this article in the video (sorry, portuguese content):

  1. Скачать любой дистрибутив для WSL2, пример будет на Ubuntu-22.04
  2. В консоли Ubuntu, в папке пользователя клонируем официальный репозиторий ядра WSL2 в папку wsl
git clone --recursive https://github.com/microsoft/WSL2-Linux-Kernel.git wsl
  1. Заходим в папку wsl и меняем там файл Microsoft/config-wsl, в нем нужно изменить Название ядра с дефолтного на свое и сохранить изменения
CONFIG_LOCALVERSION="-WSL2-CUSTOM-KERNEL"
  1. Нужно будет поставить в Ubuntu несколько пакетов для компиляции ядра, в моем случае нужны были следующие:
sudo apt update && sudo apt dist-upgrade -y
sudo apt install make build-essential flex bison libssl-dev libelf-dev dwarves
  1. При компиляции ядра могут вылезать ошибки, из-за нехватки нужных пакетов, их просто нужно доустонавливать и снова запускать компиляцию, благо она будет продолжаться с момента остановки, а не с начала.
make O=out KCONFIG_CONFIG=Microsoft/config-wsl
  1. В итоге после успешной компиляции ядра в консоли будет написан путь по которому лежит свежеиспеченное ядро, идем забираем его и копируем в какую-нибудь папку windows
#Путь до скомпилированного ядра обычно такой
\\wsl$\Ubuntu-22.04\home\user\wsl\out\arch\x86\boot\bzImage
#Копируем его, например в
C:\CutomLinuxKernel\bzImage
  1. Создаем в папке пользователя windows файл .wslconfig с таким содержанием
[wsl2]
kernel=C:\\CutomLinuxKernel\\bzImage
  1. Полностью гасим подсистему WSL2 со всеми дистрибутивами через PowerShell
wsl --shutdown
  1. Готово! Запускаем любой дистрибутив и проверяем версию ядра
uname -a
  1. Для штатного обновления ядра для WSL2 вообще предусмотренна команда wsl —update, но у меня она не работала

Уровень сложностиПростой

Время на прочтение4 мин

Количество просмотров7.6K

Мы активно пользуемся WSL2 для того, чтобы открывать линуксовые коры в Visual Studio. Для обеспечения консистентности символов и коры мы монтируем squashfs образ, созданный в целевой системе. После очередного апдейта целевого дистрибутива, у нас всё сломалось — squash монтировался, но мог посередине файла выдать ошибку чтения, записав в dmesg что-то типа

[ 17.157892] SQUASHFS error: xz decompression failed, data probably corrupt
[ 17.158705] SQUASHFS error: Failed to read block 0x5c3cb5e: -5

Естественно, точно такой же сквош на целевой системе работал как часы и никаких ошибок не выдавал.

По мере исследования выяснилось, что ядро WSL не включает опции ядра, связанные с BCJ фильтрацией в XZ.

BCJ фильтр

Алгоритм XZ это на самом деле LZMA плюс интервальное кодирование как разновидность арифметического. В свою очередь, LZMA можно очень упрощенно описать как замену одинаковых участков сжимаемого текста на ссылки ‘назад’ — сжатие по словарю, а интервальное кодирование — как выбор самого короткого числа, описывающего сжимаемый текст с точки зрения вероятностей отдельных символов в месте их появления.

Поскольку используется словарное сжатие LZMA, важно иметь много одинакового текста. А в исполняемых файлах много вызовов библиотечных функций. Эти вызовы выглядят примерно так:

   0x000000000040112a <+4>:	    bf 10 20 40 00	mov    $0x402010,%edi
   0x000000000040112f <+9>:	    e8 fc fe ff ff	call   0x401030 <puts@plt>
   0x0000000000401134 <+14>:	bf 1c 20 40 00	mov    $0x40201c,%edi
   0x0000000000401139 <+19>:	e8 f2 fe ff ff	call   0x401030 <puts@plt>

Два вызова puts() в листинге выше используют инструкцию call relative to next instruction но на самом деле указывают на одно и то же место. Если бы мы нашли все такие вызовы puts() и поменяли их с относительного адреса на абсолютный, то у нас было бы очень много одинаковых пятибайтных кусочков. То же самое справедливо для инструкций ветвления (Branch) и безусловных переходов (Jump) — отсюда и название BCJ фильтра — Branch/Call/Jump.

Естественно, такой способ подходит только для исполняемого кода и замедляет обработку — например, при тестировании сборки Fedora Linux за 30 мб cжатия от 1.7 Гб образа заплатили 18 минутами распаковки (примерно в два раза медленнее). Но кому-то и такое может зайти. Дефолт такой дефолт.

Впрочем, раз squashfs по дефолту собирается с BCJ фильтром, надо соответствующие опции включить в ядре. А для этого ядро надо пересобрать.

Сборка ядра

В качестве подопытного кролика будет выступать AlmaLinux 9 — но не так сложно найти гайды по пересборке ядра в базовой для WSL Ubuntu. В общем и целом процесс отличается от «обычной» сборки ядра для линукса только файлом настроек.

Внимание!
В отличие от линукса, NTFS регистронезависим, и поэтому могут быть проблемы с доступом к исходникам во время компиляции! Все действия этого раздела проводятся внутри WSL2 на собственной файловой системе!

Поставим всё, что для сборки понадобится:

sudo dnf install --enablerepo=crb kernel-devel bc \
   git dwarves ncurses-devel binutils{,-gold} rsync kmod

kernel-devel это немножко перебор — но зато ставит большую часть инструментария для сборки ядра.
ncurses-devel это для menuconfig — текстового интерфейса конфигурации ядра.

Скачаем исходники ядра с настройками «от Микрософт»

git clone https://github.com/microsoft/WSL2-Linux-Kernel.git --depth=1 -b linux-msft-wsl-5.15.y
cd WSL2-Linux-Kernel

На момент публикации основная ветка — linux-msft-wsl-5.15.y, следующий кандидат — linux-msft-wsl-6.1.y.
Если нужно конкретное ядро — есть таги вида linux-msft-wsl-<maj>.<min>.<x>.<y> — например, linux-msft-wsl-6.1.21.2

Файл с настройками ядра можно найти в Microsoft/config-wsl.
Теперь нужно изменить эти настройки — руками в файле или через menuconfig

make menuconfig KCONFIG_CONFIG=Microsoft/config-wsl

Конкретно для работы BCJ было достаточно добавить

CONFIG_XZ_DEC_X86=y

но в ядре есть и опции для BCJ фильтрации кода других архитектур.

Для точного определения какое ядро используется можно поменять суффикс локальной версии (General setup -> Local Version) и/или добавить git sha к суффиксу (General setup -> Automatically append version information).

Дальше — сборка ядра и установка модулей.
Базовая настройка от Микрософта не имеет настроек компиляции в модули, но вдруг именно вам надо?
Заголовки ядра тоже вещь очень на любителя.

make -j $(nproc) KCONFIG_CONFIG=Microsoft/config-wsl
make modules_install headers_install

Предупреждение — мне ни модули ни хедеры не пригодились, поэтому привожу команду только для полноты картины. Возможно, потребуется что-то ещё чтобы модули загружались автоматически.

Установка и проверка нового ядра

Если make закончился успешно, то новое ядро можно найти в arch/x86/boot/bzImage. Для использования в WSL его надо вытащить наружу

mkdir -p /mnt/c/Users/<USER>/.wsl-kernels/
cp arch/x86/boot/bzImage /mnt/c/Users/<USER>/.wsl-kernels/

WSL2 использует конфигурационный файл .wslconfig для юзероспецифичных настроек WSL.
Для использования своего ядра надо туда записать

[wsl2] 
kernel=C:\\Users\\<USER>\\.wsl-kernels\\bzImage

потом перезапустить подсистему WSL

wsl --shutdown
wsl

и потом изнутри WSL проверить какое ядро запущено

uname -r

Дополнительные ссылки

Ядерная реализация XZ в линуксе взята из https://github.com/tukaani-project/xz-embedded

LZMA — https://neerc.ifmo.ru/wiki/index.php?title=Алгоритм_LZMA, https://www.7-zip.org/sdk.html

интервальное кодирование — https://ru.wikipedia.org/wiki/Интервальное_кодирование

Другие маны по сборке ядра для WSL2:
https://github.com/Zhoneym/WSL-Docs/blob/main/WSL/compile-wsl2-kernel.md
https://alexkaouris.medium.com/run-your-own-kernel-with-wsl2-21e3143e014e

Beginning with Windows Insiders builds this Summer, we will include an in-house custom-built Linux kernel to underpin the newest version of the Windows Subsystem for Linux (WSL). This marks the first time that the Linux kernel will be included as a component in Windows. This is an exciting day for all of us on the Linux team at Microsoft and we are thrilled to be able to tell you a little bit about it.

Tuned for WSL

The term “Linux” is often used to refer both to the Linux kernel as well as the GNU userspace. As with WSL1, WSL2 will not provide any userspace binaries. Instead, the Microsoft kernel will interface with a userspace selected by the user. This will generally come through installation via the Windows store but can also be “sideloaded” through the creation of a custom distribution package. The only exception to this rule is a small init script that is injected to bootstrap the startup process, forming the connections between Windows and Linux that make WSL so magical.

The kernel itself will initially be based on version 4.19, the latest long-term stable release of Linux. The kernel will be rebased at the designation of new long-term stable releases to ensure that the WSL kernel always has the latest Linux goodness.

In addition to the LTS source from Kernel.org, a number of local patches are being applied. These patches tune the resulting binary for use in WSL2 by improving launch times, reducing the memory footprint and curating a minimal set of supported devices. The result is a small, lightweight kernel that is purpose built for WSL2 to be a drop-in replacement for the emulation architecture featured in the design of WSL1.

Code goes upstream

Microsoft employs a growing number of Linux contributors who have brought industry leading Linux knowhow into the company. For years now, these Linux developers have enabled Microsoft to support new platform features in the wide number of distributions provided in the Azure Marketplace.

An important philosophy of Linux at Microsoft is that all changes go upstream. Maintaining downstream patches adds complexity and is not standard practice in the open source community. In leveraging Linux, we are making a commitment to be good citizens and contribute back the changes that we make.

However, during development it is necessary to work with local patches that enable new features or address issues in upstream. In these cases, we either create, or find patches that fulfill our product requirements and then work with the community to get that code integrated as soon as possible. To protect the stability of the LTS branches, some patches – such as for new features – might only be included in future versions of the kernel, and not be back-ported to the current LTS version.

When the WSL kernel source becomes available it will consist of links to a set of patches in addition to the long-term stable source. Over time, we hope this list will shrink as patches make it upstream and grow as we add new local patches to support new WSL features.

Security

The WSL kernel will be built using Microsoft’s world-class CI/CD systems and serviced through Windows Update in an operation transparent to the user. The kernel will stay up to date with the newest features and fixes in the latest stable branch of Linux. To ensure the provenance of our sources we mirror repositories locally. We continually monitor Linux security mailing lists and partner with several CVE database companies to help ensure that our kernel has the most recent fixes and mitigations.

One of the great things about Linux is its stable and backwards compatible system call interface. This will enable us to ship the latest stable branch of the Linux kernel to all versions of WSL2. We will rebase the kernel when a new LTS is established and when we have sufficiently validated it.

Open Source

The kernel provided for WSL2 will be fully open source! When WSL2 is released in Windows Insider builds, instructions for creating your own WSL kernel will be made available on Github. We will work with developers interested in contributing to help get changes upstream. Check back in a few weeks for more information.

Thanks!

This is the culmination of years of effort from the Linux Systems Group as well as multiple other teams across Microsoft. We are excited to be able to share the result and look forward to the new and interesting ways in which you will use WSL. If you are interested in positions at Microsoft working with Linux check out this job listing.

Author

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

Создание микросервисов с Domain-Driven Design

ArchitectMsa 04.05.2025

Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .

Многопоточность в C++: Современные техники C++26

bytestream 04.05.2025

C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ошибка 0х80070005 при запуске службы windows audio
  • Windows 10 mobile поддерживаемые устройства
  • Install sccm client on windows 10
  • Программа для измерения времени загрузки windows
  • Windows 10 х32 lite