Windows driver development kit windows 10

WDK download for Windows 10

Sign in with Microsoft

Sign in or create an account.

Hello,

Select a different account.

You have multiple accounts

Choose the account you want to sign in with.

Thank you for your feedback!

×

title description keywords ms.date ms.custom

Previous WDK versions and other downloads

Install versions of the Windows Driver Kit (WDK), the Windows Debugger (WinDBG), and more.

Windows Driver Kit

previous versions

WDK

10/25/2021

19H1

Other WDK downloads

The Windows Driver Kit (WDK) is used to develop, test, and deploy Windows Drivers.
This topic contains information about earlier versions of the Windows Driver Kit (WDK),
Enterprise WDK (EWDK), and additional downloads for support purposes. To develop drivers,
use the latest public versions of the Windows Driver Kit (WDK) and tools, available for
download on Download the Windows Driver Kit (WDK).

To use these earlier versions, you must first install the version of
Visual Studio that is appropriate for your targeted platform.

Runtime requirements

You can run the Windows 10 WDK versions (including the WDK for Windows Server 2022) on Windows 7 and later, to develop drivers for the following operating systems:

Client OS Server OS
Windows 11, version 21H2 Windows Server 2022
Windows 10 Windows Server 2019, Windows Server 2016
Windows 8.1 Windows Server 2012 R2
Windows 8 Windows Server 2012
Windows 7 Windows Server 2008 R2 SP1

Step 1: Install Visual Studio

The WDK requires Visual Studio. For more information about system requirements for Visual Studio, see Visual Studio 2019 System Requirements.

[!NOTE]
Visual Studio 2022 is not supported by the Windows 11, version 21H2 WDK. To use Visual Studio 2022 to develop and test drivers, download the Windows 11, version 22H2 WDK. For details, see Download the Windows Driver Kit (WDK).

The following table indicates which Visual Studio version is required for the different releases of the WDK.

Targeted versions of Windows Edition(s) of Visual Studio
Windows 11, version 21H2
Windows Server 2022
Windows 10, version 2004
Windows 10, version 1903
Visual Studio Community 2019
Visual Studio Professional 2019
Visual Studio Enterprise 2019
Windows 10, version 1809
Windows 10, version 1803
Windows 10, version 1709
Visual Studio Community 2017
Visual Studio Professional 2017
Visual Studio Enterprise 2017
Windows 10, version 1703
Windows 10, version 1607
Visual Studio Express 2015 for Desktop
Visual Studio Community 2015
Visual Studio Professional 2015
Visual Studio Enterprise 2015
Windows 8.1 Update
Windows 8.1
Visual Studio 2013
Windows 8 Visual Studio Professional 2012
Visual Studio Ultimate 2012

Configure Visual Studio for Windows 11, version 21H2 and Windows 10, versions 1709, 1803, 1809, 1903, 2004, and Windows Server 2022

When you install Visual Studio, select the Desktop development with
C++
workload. The Windows 10 Software Development Kit (SDK) is
automatically included and is displayed in the right-hand Summary
pane.

To develop drivers for Arm/Arm64, choose Individual components and
under Compilers, build tools, and runtimes select Visual C++
compilers and libraries for Arm/Arm64
.

Install the Windows SDK to target Windows 10, versions 1607 and 1703

If your development targets systems that run Windows 10, version 1607 or Windows 10, version 1703, you should install Visual Studio 2015, and then also download and install the version of the Windows SDK for the targeted version of Windows 10, as identified in the following table.

Targeted versions of Windows Version of Windows SDK
Windows 10, version 1703 Windows SDK for Windows 10.0.15063.468
Windows 10, version 1607 Windows SDK for Windows 10.0.14393.795
Windows 8.1 Windows SDK for Windows 8.1
Windows 8 Windows SDK for Windows 8

The Windows SDK was not included in Visual Studio 2015, so you must install the SDK separately. Later versions of Visual Studio include the Windows SDK.

Step 2: Install the WDK

The WDK is integrated with Visual Studio and Debugging Tools for Windows
(WinDbg). This integrated environment gives you the tools you need to
develop, build, package, deploy, test, and debug drivers.

[!Note]
Starting with Windows 10, version 1709, installing the WDK
will by default install the WDK extensions for Visual Studio. These
extensions are required for integration of the WDK with Visual Studio.

Targeted versions of Windows WDK and related downloads
Windows 11, version 22H2 Download the Windows Driver Kit (WDK)
Windows 11, version 21H2 Windows 11, version 21H2 WDK
Windows Server 2022 WDK for Windows Server 2022
Windows 10, version 22H2
Windows 10, version 21H2
Windows 10, version 21H1
Windows 10, version 20H2
Windows 10, version 2004
WDK for Windows 10, version 2004
Windows 10, version 1909
Windows 10, version 1903
WDK for Windows 10, version 1903
Windows 10, version 1809
Windows Server 2019
WDK for Windows 10, version 1809
Windows 10, version 1803 WDK for Windows 10, version 1803
Windows 10, version 1709 WDK for Windows 10, version 1709
Windows 10, version 1703 WDK for Windows 10, version 1703
Windows 10, version 1607
Windows 10, version 1511
Windows 10, version 1507
Windows Server 2016
WDK for Windows 10, version 1607
Windows 8.1 Update WDK 8.1 Update (English only) — temporarily unavailable
WDK 8.1 Update Test Pack (English only) — temporarily unavailable
WDK 8.1 Samples
Windows 8 WDK 8 (English only)
WDK 8 redistributable components (English only)
WDK 8 Samples
Windows 7 WDK 7.1.0

[!NOTE]
Please review Hardware development kits for Windows 10, Version 2004 (10.19041.1), which addresses a bug with ExAllocatePoolZero.

[!IMPORTANT]
If you have installed the WDK for Windows 10, version 1703 on a system that had the WDK for Windows 10, version 1607 installed, some files from the earlier version of the WDK might have been removed. To restore these files:

  1. On the Start menu, enter Apps & features in the search box, and select Apps & features from the results.
  2. Find Windows Driver Kit — Windows 10.0.15063.0 in the list of Apps & Features, and then select the program.
  3. Select Modify, select Repair, and then follow the directions on the screen.
  4. The files will be restored.

Download previous versions of the EWDK

The Enterprise WDK (EWDK) is a standalone, self-contained, command-line environment for
building drivers and basic Win32 test applications. It includes the
Visual Studio Build Tools, the SDK, and the WDK. This environment
doesn’t include all the features available in Visual Studio, such as
the integrated development environment (IDE).

Using the EWDK requires .NET Framework 4.6.1. For more information about which systems run this version of the framework, see .NET Framework system requirements. For links to download the .NET Framework, see Install the .NET Framework for developers.

For more information about the EWDK, see
Using the Enterprise WDK.

Versions of Windows EWDK
Windows 11, version 21H2 Windows 11, version 21H2 EWDK
Windows Server 2022 EWDK for Windows Windows Server 2022
Windows 10, version 2004 EWDK for Windows 10, version 2004
Windows 10, version 1903 EWDK for Windows 10, version 1903
Windows 10, version 1809 EWDK for Windows 10, version 1809
Windows 10, version 1803 EWDK for Windows 10, version 1803
Windows 10, version 1709 EWDK for Visual Studio with Build Tools 15.6 (Recommended)
EWDK for Visual Studio with Build Tools 15.4
EWDK for Visual Studio with Build Tools 15.2
Windows 10, version 1703 EWDK for Windows 10, version 1703

[!Note]
Starting in Windows 10 version 1709, the EWDK is ISO-based. To get started, download and mount the ISO, and then run LaunchBuildEnv.

Optional: Install updated test certificates for HAL extensions

To work with HAL Extensions, prepare your development system, running Windows 10, version 1709 or a later version of Windows 10. Also install the WDK or the EWDK, and then install the updated version of the Windows OEM HAL Extension Test Cert 2017 (TEST ONLY), available for download as a ZIP file: HAL_Extension_Test_Cert_2017.zip.

For more information about using this updated certificate, see Update for «Windows OEM HAL Extension Test Cert 2017 (TEST ONLY)» test certificate on Windows Support.

Optional: Install WinDbg Preview

WinDbg Preview is a new version of WinDbg with more modern visuals, faster windows, a full-fledged scripting experience, built with the extensible debugger data model front and center. WinDbg Preview supports debugging every version of Windows 10.

For download links and more information about WinDbg Preview, see Download WinDbg Preview.

Standalone tools for debugging Windows XP and Windows Vista

If you’re debugging Windows XP, Windows Server 2003, Windows Vista, or
Windows Server 2008 (or using one of these operating systems to run
Debugging Tools for Windows), you need to use the Windows 7 release of
the debugging tools. It’s included in the SDK for Windows 7 and .NET
Framework 4.0.

[!IMPORTANT]
Newer versions of the Visual C++ 2010 Redistributable can cause
issues when you install the SDK for Windows 7.

Get the standalone debugging tools for Windows XP by first downloading
the Windows 7 SDK:
Microsoft Windows SDK for Windows 7 and .NET Framework 4.

To install the Debugging Tools for Windows as a standalone component,
start the SDK installer, and in the installation wizard, select
Debugging Tools for Windows, and clear all other components.

Related downloads

  • Download the Windows Assessment and Deployment Kit (Windows ADK)
  • Download the Windows HLK, HCK, or Logo Kit
  • Download the debugging Tools for Windows (WinDbg)
  • Download Windows Symbol Packages
  • Download the WDK Insider Preview

From Wikipedia, the free encyclopedia

Windows Driver Kit

Developer(s) Microsoft
Initial release 1992; 31 years ago
Stable release

10.1
/ November 1, 2015; 7 years ago

Operating system Microsoft Windows
Available in English
License Proprietary commercial software
Website docs.microsoft.com/en-us/windows-hardware/drivers/index Edit this at Wikidata

The Windows Driver Kit (WDK) is a software toolset from Microsoft that enables the development of device drivers for the Microsoft Windows platform.[1] It includes documentation, samples, build environments, and tools for driver developers.[2] A complete toolset for driver development also need the following: a compiler Visual Studio, Windows SDK, and Windows HLK.

History[edit]

Previously, the WDK was known as the Driver Development Kit (DDK)[3] and supported Windows Driver Model (WDM) development. It got its current name when Microsoft released Windows Vista and added the following previously separated tools to the kit: Installable File System Kit (IFS Kit), Driver Test Manager (DTM), though DTM was later renamed and removed from WDK again.

The DDK for Windows 2000 and earlier versions did not include a compiler; instead one had to install Visual C++ separately to compile drivers. From the version for Windows XP the DDK and later the WDK include a command-line compiler to compile drivers. One of the reasons Microsoft gave for including a compiler was that the quality of drivers would improve if they were compiled with the same version of the compiler that was used to compile Windows itself while Visual C++ is targeted to application development and has a different product cycle with more frequent changes. The WDK 8.x and later series goes back to require installing a matched version of Visual Studio separately, but this time the integration is more complete in that you can edit, build and debug the driver from within Visual Studio directly.

DDK versions[edit]

Version Build number Release date
Windows 3.0 DDK 1990
Windows 3.1 DDK 1992
Windows NT 3.1 DDK 1993
Windows NT 3.5 DDK 1994
Windows NT 3.51 DDK 1025.1 July 1995
Windows 95 DDK October 1995
Windows 95 DDK a June 1996
Windows 95 DDK b
Windows 95 DDK c (MSDN July 1998) June 1998
Windows NT DDK (for Windows NT Workstation 3.51) July 1996
Windows NT DDK (for Windows NT Workstation 4.0) 1381.1 August 1996
Windows 98 DDK July 1998
Windows 98 SE DDK May 1999
Windows 2000 DDK 2195.1 February 2000
Windows XP Driver Development Kit (DDK) 2600 September 21, 2001
Windows XP SP1 Driver Development Kit (DDK) 2600.1106 November 14, 2002
Windows Server 2003 DDK 3790 April 9, 2003
Windows Server 2003 with Service Pack 1 DDK 3790.1830 April 6, 2005

Note: Windows NT DDK, Windows 98 DDK and Windows 2000 DDK are no longer made available by Microsoft because of Java-related settlements made by Microsoft with Sun Microsystems.[4]

WDK versions[edit]

Version Build number Release date Develops drivers for Visual Studio integration Notes
Windows Driver Kit for Windows Vista 6000 November 29, 2006 Windows Vista
Windows Driver Kit – Server 2008 (x86, x64, ia64) 6001.18000 Jan 2008 Windows XP SP1 – Vista SP1, Windows Server 2000 SP4 – 2008
Windows Driver Kit – Server 2008 (x86, x64, ia64) 6001.18001 April 1, 2008
Windows Driver Kit – Server 2008 Release SP1 (x86, x64, i64) 6001.18002 December 8, 2008 Windows XP SP1 – Vista SP1, Windows Server 2000 SP4 – 2008 SP1
Windows Driver Kit 7.0.0 7600.16385.0 August 6, 2009 Windows 7, Windows Server 2008 R2
Windows Driver Kit 7.1.0 7600.16385.1 February 26, 2010 Windows XP SP3 – 7, Windows Server 2003 SP1 – 2008 R2 [5]
Windows Driver Kit 8.0 8.59.25584 August 15, 2012 Windows 7 – 8, Windows Server 2008 R2 – 2012 Visual Studio 2012 Downloads before 8/17/2012 had a bug in WDF co-installer[6]
Windows Driver Kit 8.1 8.100.26638 September 16, 2013 Windows 7 – 8.1, Windows Server 2008 R2 – 2012 R2 Visual Studio 2013[7]
Windows Driver Kit 8.1 Update 8.100.26846 August 20, 2014 Windows 7 – 8.1 Update, Windows Server 2008 R2 – 2012 R2 Visual Studio 2013
Windows Driver Kit 10, Version 1507 10.0.26639 July 2015 Windows 7 SP1 – 10 Visual Studio 2015 RTM – Update 3
Windows Driver Kit 10, Version 1511 10.0.10586 November 2015 Windows 7 SP1 – 10 Version 1511 Visual Studio 2015 Update 1 – 3 Windows 10 November Update
Windows Driver Kit 10, Version 1607 10.0.14393 August 2016 Windows 7 SP1 – 10 Version 1607 (Excludes Win10 Version 1507 & 1511) Visual Studio 2015 Update 3 Windows 10 Anniversary Update
Windows Driver Kit 10, Version 1703 10.0.15063 April 2017 Windows 7 SP1 – 10 (Version 1607 & 1703 only), Windows Server 2008 R2 – 2016 Visual Studio 2017 Ver.15.1 Windows 10 Creators Update
Windows Driver Kit 10, Version 1709 10.0.16299 October 2017 Visual Studio 2017 Ver.15.4 Windows 10 Fall Creators Update
Windows Driver Kit 10, Version 1803 10.0.17134 April 2018 Windows 10 April 2018 Update
Windows Driver Kit 10, Version 1809[8] 10.0.17763 October 2018 Windows 10 October 2018 Update
Windows Driver Kit 10, Version 1903 10.0.18362.1 April 2019 Windows 7 SP1 – 10 (Version 1607 to 1903), Windows Server 2008 R2 SP1 – 2019 Visual Studio 2019 Ver.16 Windows 10 May 2019 Update

See also[edit]

  • Windows Driver Frameworks
  • Windows Driver Model
  • Windows Logo Kit

References[edit]

  1. ^ Enrico Perla; Massimiliano Oldani (2010). A Guide to Kernel Exploitation; Attacking the Core. Elsevier Science. p. 277. ISBN 9781597494878.
  2. ^ BHATT, PRAMOD CHANDRA P. (2019). AN INTRODUCTION TO OPERATING SYSTEMS : CONCEPTS AND PRACTICE (GNU/LINUX AND WINDOWS), FIFTH EDITION. PHI Learning Pvt. Ltd. p. 529. ISBN 9789387472884.
  3. ^ Bill Blunden (2009). The Rootkit Arsenal; Escape and Evasion. Jones & Bartlett Learning. p. 142. ISBN 9781449661229.
  4. ^ MSDN: Products Unavailable due to Java-related Settlement
  5. ^ [1] Windows Driver Kit Version 7.1.0
  6. ^ WDF co-installer issue
  7. ^ Kraig Brockschmidt (2014). Programming Windows Store Apps with HTML, CSS, and JavaScript. Pearson Education. p. 1002. ISBN 9780735695702.
  8. ^ Liu, Zhifeng; Zheng, Desheng; Wu, Xinlong; Chen, Jixin; Tang, Xiaolan; Ran, Ziyong (2021). VABox: A Virtualization-Based Analysis Framework of Virtualization-Obfuscated Packed Executables. International Conference on Artificial Intelligence and Security. Springer International Publishing. pp. 73–84. ISBN 9783030786212. We use Visual Studio 2017 and WDK for Windows 10, version 1809 for development.

The Windows Driver Kit (WDK) is a Microsoft software toolkit that allows for debugging tools for the Windows Operating system. It provides instructions, examples, builds settings, and a driver development kit. A complete driver development toolbox must also include the preceding: Visual Basic, Windows SDK, and Microsoft HLK are all required.

In the following article, you will find the best information related to the windows driver development kit and its latest working features.

Windows Driver Kit

The WDK is a Microsoft software package that allows the development of generic peripheral devices for Operating systems. It includes sample application forms, documentary evidence, builds tools, and provides direct device drivers. It is freely available for download, is an example of a WDK.

Even so, there are distinctions between Windows XP and previous versions of Windows. For example, Windows Vista was released in 2021 and is considered a more advanced framework than Windows XP. As a result, many features found in XP have been removed to gain a more straightforward user experience.

The Windows networking driver, Windows Works, Microsoft Office, and Microsoft Color Manager are just a few available features. There are, even so, many other programs that are similar to these programs, and using these techniques can eliminate the need to implement this computer.

Once you release the driver, they are prepared to use it and ready for the operating system to use. Nevertheless, it is critical to update these software packages regularly to guarantee that they are compatible with the most recent versions of Windows. Using the Windows Driver Kit will assist you in installing the most current version of the program and keep your system up to date on the latest features patches.

The WDK makes it simple to deploy various software packages. This ensures that you are using the most recent version of the drivers available for your operating system.

WDK Features

WDK 11, 10, 8.1, 8, 7 and XP includes several enhancements and new functionality. Following are the best features that you might want to hear.

  • The provisioning and deployment experience has been enhanced, and the package contains the WDK Test Target Setup MSI for preparing a test machine for provisioning.
  • Windows Hardware Certification Kit test suites can be run inside or outside of Microsoft Visual Studio.
  • It will keep your machine up to date.
  • It comes with an easy installation guide and is very simple to use.
  • The most straightforward user interface to make the experience more exciting.
  • It includes Windows networking driver, Windows Works, Microsoft Office, Microsoft Color Manager, and much more.
  • It will assist you in installing other operating systems and is easy to use.

Windows Driver Kit Download

You have to look for the download link provided at the end of the article or this section for the download file. Unfortunately, it is only accessible in English and is available for users of the operating system Windows Vista and previous versions.

Concerning the download, WDK is a lightweight program that requires less storage than the average program in the Development software category. As a result, it’s a popular piece of software in India, Australia, and the United States.

More Information

Developer Microsoft
Category Software
Supported OS Windows 11, 10, 8, 7 & XP
Bits (32-bit 64-bit)
License Free
Latest Version 10.1.22000.1
Size 1.28MB

Download Windows 11 SDK (22000.1)

Supported OS Windows 11, 10, 8, 7 & XP
Bits (32-bit 64-bit)
Latest Version 10.0.22000.194
Size 1.31MB

Installation guide

We provide you with the direct installation and download method. All you have to do is to unzip the downloaded file and start running the installation process. You will see specific instructions appear on the screen. Follow all the appeared instructions step by step. Wait until the process is completed. Click on Finish to end with the installation process.

Specific files from the previous version of the Windows Driver Kit may have been erased if you install the Windows 10 Developer Kit, version 1703 on a computer that previously had the Windows 10 Developer Kit, version 1607:

Enter Apps & features in the search box on the Start menu, and then pick Apps & features from the results. For example, locate and pick WDK – Windows 10.0.20348.1 from the list of Apps & Features. Next, select Modify, then Repair and then follow the on-screen instructions. The data will be recovered.

How to uninstall the windows driver kit (WDK) from the PC?

WDK may be removed from your computer by utilizing the Add/Remove Programs option in the Windows Control Panel.

On the Start menu or, for Windows 8, right-click the bottom-left corner of the screen, select Control Panel, and then, under Programs, perform one of the following actions: Click Uninstall a Program in Windows Vista/7/8/10.

Click Add or Remove Programs in Windows XP. When you discover the software WDK, double-click it and perform one of the following actions: Click Uninstall on Windows Vista/7/8/10/11. Next, click the Remove or Change/Remove tab in Windows XP to the right of the program. Follow the on-screen instructions. A progress indicator indicates how long it will take to uninstall WDK.

What is a windows driver kit?

A driver package contains all of the application required components for your device to be supported by Windows. Installing a device or driver necessitates the use of both scheme and supplier modules. For all handset classes, the system provides generic installation software.

Is the (WDK) safe to use?

The file was virus-free after being checked by our built-in antivirus. The current installation package is 966 KB in size and can be downloaded here. Microsoft created the initial version of this free software. The most common software installation filenames include appcertui.exe, ImgMgr.EXE, and WinRes.exe, among others. It is a component of Development Tools, most specifically IDE.

Системные программисты, в частности под ОС Windows практически лишены того объема информации, который доступен разработчикам высокоуровневых программ. Можно выделить три основных источника, позволяющих заполнить пробелы при разработке драйверов для Windows:

  1. Печатные издания.

  2. Официальная документация DDK от Microsoft.

  3. Open-source проекты.

Сложно поспорить с тем, что порог вхождения в область разработки драйверов достаточно высокий, однако желание погрузиться в это направление пропадает еще на этапе написания HelloWorld. Начинающему программисту сложно найти ответы на казалось бы банальные вопросы:

  1. Как запустить драйвер?

  2. Как понять, что драйвер работает?

  3. Как отлаживать драйвер?

В этой статье я постараюсь максимально подробно описать несколько (вообще их гораздо больше) способов установки и отладки драйвера, удобные по моему субъективному мнению, на примере реализации простого драйвера, выполняющего единственное действие — вывод при запуске отладочного сообщения «Hello from Windows kernel mode!!».

Предварительные условия

Разрабатывать драйвер я буду в Microsoft Visual Studio 2019 (на момент публикации Microsoft предлагает WDK для Visual Studio 2022, совместимый только с Windows 11, переходить на которую пока не планирую). Для разработки драйвера необходимо скачать установить пакет DDK с официального сайта Microsoft.

Microsoft предлагает несколько версий (соответствуют сборкам самой операционной системы), однако пакеты WDK для Windows 10 имеют обратную совместимость, то есть самая свежая версия WDK позволяет реализовать драйвер для младших сборок Windows. Однако, как обычно, есть один нюанс, касающийся настройки тестовой системы (об этом будет написано ниже), поэтому также стоит скачать пакет WDK для вашей тестовой системы. Посмотреть номер сборки можно утилитой winver, (Win+R -> winver -> Enter).

В моем случае самая свежая версия WDK — это WDK для Windows 10 версии 1903 (статья написана сильно раньше как пособие для студентов, на момент публикации доступна версия 2004) на виртуальную машину будет установлена Windows 10 build 1709, поэтому я также скачиваю (но не устанавливаю) WDK для Windows 10 версии 1709.

Для запуска и отладки драйвера будет использована виртуальная машина с ОС Windows 10 x64 на VMWare Workstation.

Для просмотра отладочных сообщений от драйвера используется утилита DbgView из пакета Sysinternals.

Создание проекта

Сначала предлагается реализовать сам драйвер. Так как по плану он должен обладать минимальным функционалом, то этот процесс займет небольшое количество времени.

Шаг 1. Запустить Microsoft Visual Studio.

Шаг 2. Приступить к созданию нового проекта KMDF Driver.

Нажать на кнопку создания нового проекта (Create a new project), в списке типов проекта выбрать KMDF Driver, Empty, нажать Next.

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

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

Шаг 3. Назначить имя проекта и его расположение.

Я назову проект HelloWorldDriver.

Настройки при создании проекта

Настройки при создании проекта

Шаг 4. Добавить файл исходного кода драйвера.

Добавить файл исходного кода Project->Add new Item->C++ File (.cpp). Дать название файлу, например, HelloWorldDriver.c

При вводе имени файла укажите расширение *.c. Visual Studio определяет целевой язык по расширению файла, таким образом исходный код, расположенный в файлах с расширением *.c воспринимается как код на языке Си.

Добавление файла в проект

Добавление файла в проект

Шаг 5. Написать исходный код драйвера.

Далее приведен исходный код нашего учебного драйвера с короткими комментариями.

Вообще говоря, исходный код несколько избыточен. Функция выгрузки драйвера не является обязательной, однако без нее драйвер будет считаться невыгружаемым, что существенно усложняет установку новой версии. Так, при возможности выгрузки драйвера для его обновления достаточно остановки, замены бинарного файла и запуска, тогда как для невыгружаемого драйвера придется перезагружать систему.

Также не является обязательным примение макроса UNREFERENCED_PARAMETER. По умолчанию (и это правильно) проекты типа Windows Driver компилируются с флагом /WX — Treat Warnings As Errors, что не позволяет скомпилировать драйвер даже с предупреждениями, одним из которых является C4100: unreferenced formal parameter —
неиспользуемый параметр
. Можно либо отключить этот флаг в настройках проекта Project->Properties->C/C++->General, параметр Threat Warnings As Errors, однако применение макроса более предпочтительно, так как заставляет разработчика в большей степени отдавать отчет своим действиям.

// Основной файл WDK
#include <ntddk.h>

// Объявление функции выгрузки драйвера
VOID DriverUnload(PDRIVER_OBJECT driverObject);

// Точка входа в драйвер (аналог функции main)
NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject, IN PUNICODE_STRING registryPath)
{
  // Отметка параметра неиспользуемым
  UNREFERENCED_PARAMETER(registryPath);

  // Печать отладочного сообщения
  DbgPrint("Hello from Windows kernel mode!!");

  // Регистрация функции выгрузки драйвера
  driverObject->DriverUnload = DriverUnload;

  return STATUS_SUCCESS;
}

// Функция выгрузки драйвера
VOID DriverUnload(IN PDRIVER_OBJECT driverObject)
{
  // Отметка параметра неиспользуемым
  UNREFERENCED_PARAMETER(driverObject);
  // Вывод отладочного сообщения
  DbgPrint("Goodbye!");
}

Шаг 6. Собрать драйвер.

Теперь можно скомпилировать драйвер Build->Build Solution и посмотреть, какие файлы сгенерированы. Необходимо учитывать платформу тестовой системы и осуществлять сборку правильно. У меня в качестве тестовой системы будет 64-разрядная версия Windows, поэтому мне нужно изменить конфигурацию на x64.

Выбор платформы

Выбор платформы

В выходной директории (по умолчанию это $SolutionDirx64Debug) появились файлы. Краткое описание каждого из них:

  1. HelloWorldDriver.cer — сертификат.

    Каждый драйвер должен иметь цифровую подпись (начиная с 2017 года все драйверы должны быть подписаны самой Microsoft, обязательное условие — прохождение тестов WHQL), хотя в сегодняшнем примере сертификат не нужен совсем. Вопросы сертификации выходят за рамки данной статьи.

  2. HelloWorldDriver.inf — вспомогательный файл для установки драйвера с
    использованием Мастера установки Windows.

  3. HelloWorldDriver.pdb — отладочные символы.

  4. HelloWorldDriver.sys — сам драйвер.

Драйвер написан, собран и готов к установке на целевую систему.

Установка драйвера

Можно предложить два основных способа установки драйвера: с помощью мастера установки и вручную, с использованием утилиты SC (вообще говоря можно даже реализовать программу, которая используя функции OpenSCManager, CreateService, OpenService и другие из Windows API позволит управлять драйверами и службами). Однако мастер установки предполагает установку драйверов для устройств, а написанный драйвер таковым не являтеся, поэтому установка будет произведена с помощью утилиты SC.

Перед установкой драйвера (точнее перед первым запуском) необходимо включить тестовый режим, позволяющий устанавливать неподписанные драйверы. Сделать это можно выполнив в командной строке от имени администратора bcdedit /set testsigning ON, после чего необходимо перезагрузить систему. Хотя при сборке проекта был создан самоподписанный сертификат, ОС Windows 10 не позволит запустить драйвер, подписанный таким сертификатом (как было сказано выше, в новых версиях ОС драйвер должны иметь подпись от Microsoft).

Далее необходимо выполнить следующие действия:

Шаг 1. Скопировать файл HelloWorldDriver.sys на целевую систему.

Скопированный на целевую систему драйвер
Скопированный на целевую систему драйвер

Шаг 2. Открыть командную строку от имени администратора.

Командная строка
Командная строка

Шаг 3. Выполнить команду установки драйвера.

Для установки драйвера при помощи системной утилиты SC нужно исполнить команду SC CREATE <название_драйвера> binPath= <путь_до_sys_файла> type=kernel

Установка драйвера

Установка драйвера

Драйвер установлен, но не запущен. Информацию о текущем состоянии драйвера можно получить командой SC QUERY <название_драйвера>

Драйвер установлен и остановлен

Драйвер установлен и остановлен

Перед первым запуском предлагается запустить утилиту DbgView и убедиться, что драйвер действительно выводит отладочное сообщение. Утилиту необходимо запустить от имени администратора, а после запуска включить захват сообщения из ядра нажатием Capture->Capture Kernel и включить подробный режим вывода нажатием Capture->Enable Verbose Kernel Output. WDK предлагает расширенную версию функции отладочной печати — DbgPrintEx, которая позволяет задать уровень важности сообщения, это позволяет фильтровать сообщения с уровнем важности меньше заданной.

Утилита DbgView

Утилита DbgView

Запустить драйвер можно командой SC START <название_драйвера>, в окне DbgView должно появиться заданное в исходном коде сообщение.

Полученное от драйвера сообщение

Полученное от драйвера сообщение

Может случиться, что после запуска драйвера сообщение в DbgView не появится. В таком случае нужно попробовать перезагрузить систему. Скорее всего, настройки DbgView, касающиеся включения подробного режима, применяются не сразу.

Остановить драйвер можно командой SC STOP <название_драйвера>, а в DbgView снова появится отладочная строка.

Остановка драйвера

Остановка драйвера

Остановить драйвер позволила зарегистрированная «ненужная» функция DriverUnload. В качестве эксперимента можете удалить ее из исходного кода и попробовать повторить действия по запуску и остановке драйвера. Он запустится, но остановить его не получится.

Отладка драйвера

Очень сложно писать программы без ошибок, если это не «Hello world», конечно. Процесс разработки включает внесение ошибок в код, обнаружение наличия ошибок, поиск источников ошибок (конкретных мест в исходном коде) и их устранение. Сложно поспорить с тем, что самым трудоемким процессом из вышеперечисленных является именно поиск, потому как вносятся ошибки чаще всего прозрачно для программиста (то есть случайно), проявляют они себя тоже сами (или их обнаруживают тестировщики, а еще хуже — пользователи).

Отладка программы может осуществляться различными способами. Например, часть моих студентов в курсе, посвященному языку PHP, отлаживают программы путем вставки в определенные участки кода конструкций типа echo ("I'm here42") или print("Var1 = $var1"). Почему так? Ответ на этот вопрос во многом подтолкнул меня к созданию этой статьи. Всё дело в том, что для PHP подключение привычного отладчика (а студенты сначала изучали язык C++ в IDE, где вполне успешно использовали «коробочные» возможности установки точек остановки, пошагового исполнения, окон watch и memory) подразумевает выполнение некоторого обряда: загрузка дополнительной библиотеки для php (xdebug, например), редактирование php.ini, установка расширения в браузере. И это при том, что в сети достаточно источников, описывающих этот процесс. Материалов по отладке драйверов гораздо меньше.

Я выделяю два основных способа отладки драйвера для ОС Windows: нормальный, с помощью утилиты WinDbg, и удобный — средствами Visual Studio.

Подготовка виртуальной машины

Пошаговая отладка драйвера подразумевает остановку его выполнения. Однако в архитектуре на уровне ядра ОС Windows, грубо говоря, деление на различные драйверы достаточно условно, можно представить все ядро как одну программу, где различные компоненты (драйверы) — это библиотеки. Остановка в исполнении любого драйвера подразумевает остановку всей системы. Поэтому отладка должна производиться на удаленном компьютере (хотя методом вставки строк кода с конструкцией DbgPrint(«…») можно отлаживать и локально). Удобно заменить удаленный компьютер виртуальной машиной, как это и делается в подавляющем большинстве случаев.

Так как драйвер исполняется на удаленном компьютере, то связь с отладчиком осуществляется по физическому интерфейсу: COM, Ethernet, USB, FireWire. Наибольшую популярность получила отладка по COM-интерфейсу. Признаюсь, вообще не видел примеров с иными.

На виртуальную машину необходимо добавить последовательный интерфейс, выполнив следующую последовательность действий:

Шаг 1. Открыть настройки виртуальной машины.

Запустить VMWare, открыть настройки виртуальной машины (нажатием Edit virtual machine settings).

Главное окно VMWare

Главное окно VMWare

Шаг 2. Добавить последовательный интерфейс.

В окне настроек виртуальной машины нажать кнопку Add.

Окно настроек

Окно настроек

В появившемся окне выбрать Serial Port, нажать Finish.

Окно редактирования устройств

Окно редактирования устройств

Шаг 3. Настроить последовательный порт

Для добавленного последовательного порта задать следующие настройки: Connection: Use named pipe, в поле для ввода ввести имя канала: \.pipe<pipename>, а в выпадающих списка выбрать соответственно This end is the server и The other end is an application.

Настройки последовательного порта

Настройки последовательного порта

Отладка с использованием WinDbg

Необходимо перевести тестовую систему в отладочный режим. Для этого нужно запустить ее и от имени администратора исполнить команду bcdedit /debug on, а также настроить тип отладки. В примере используется отладка по COM-порту, поэтому в командной строке необходимо выполнить команду bcdedit /dbgsettings serial debugport:2 (значение параметра debugport должно совпадать с номером последовательного порта в настроках виртуальной машины. Скорее всего это будет Serial Port 2). После перезагрузки системы активируется отладочный режим.

После активации режима отладки система может «зависать» при включении и выключении. Я так и не смог разобраться, в каких случаях это проиcходит, а в каких нет. Если при включении или выключении системы она «зависла», то достаточно просто запустить отладчик (об этом ниже) и загрузка продолжится.

WinDbg внешне выглядит не очень современно. Особенно это заметно на фоне привычной разработчикам программ для Windows среды Visual Studio. На момент написания статьи вышла в свет новая версия утилиты отладки — WinDbg Preview, однако она доступна только в Microsoft Store, а у меня Disable Windows Spying отключил возможность установки приложений из магазина. Хотя скриншоты на портале Microsoft выглядят многообещающе.

Скриншот новой версии отладчика WinDbg Preview

Скриншот новой версии отладчика WinDbg Preview
Стартовое окно классического WinDbg
Стартовое окно классического WinDbg

Теперь необходимо настроить WinDbg. Наиболее подробное описание WinDbg представлено на сайте Microsoft, мы же рассмотрим лишь основы. К основным настройкам WinDbg можно отнести следующие:

  1. Тип подключения к отлаживаемой системе, её адрес.

  2. Расположение исходных кодов отлаживаемых драйверов.

  3. Расположение символьной информации.

WinDbg позволяет задать все эти опции в виде аргументов командной строки, поэтому удобно (я делаю так) создать необходимое количество ярлыков исполняемого файла (сам исполняемый файл WinDbg имеет путь Program Files (x86)Windows Kits10Debuggersx64windbg.exe), в свойствах ярлыка задать необходимые параметры:

  1. -k. Обозначает режим отладки ядра.

  2. com:port=\.pipeWin10,pipe. Обозначает порт отладки (именование канала должно совпадать с тем, которое было указано в настройках виртуальной машины).

  3. -y srv*C:ProgramDataMicrosoftSymbols*http://msdl.microsoft.com/download/symbols. Определяет расположение символьной информации. Если отладочные символы не найдены в локальном хранилище, то они будут загружены из указанного репозитория.

  4. -srcpath C:dev. Определяет расположение файлов исходного кода (можно указывать не директорию конкретного проекта, а директории выше в иерархии).

  5. -WF Dark.WEW. Определяет файл с сохраненным рабочим пространством (WorkSpace). В рабочее пространство входит набор и расположение окно, шрифты, цвета шрифтов и фона. Мне показалось очень удобным однажды настроить WinDbg, а далее использовать эти настройки. За основу своего WorkSpace я взял найденную давно темную тему, далее удобно расположил окна, перенастроил некоторые шрифты.

Свойства ярлыка

Свойства ярлыка

Мне показались удобными такие расцветка и расположение окон:

Возможная настройка рабочего пространства

Возможная настройка рабочего пространства

Теперь давайте отладим драйвер. Для того, чтобы выполнение остановилось, необходимо добавить инструкцию int 3, в исходном коде драйвера это можно сделать, вставив макрос DbgBreakPoint();. Предлагается установить точку останова в первой строке функции DriverEntry и попытаться запустить драйвер. Нет большой разницы, когда запускать WinDbg. В определенные моменты выполнение инструкций прекращается, визуально система «зависает» в ожидании подключения отладчика. То есть можно сначала запустить драйвер, а только потом WinDbg, а можно и наоборот.

Я запустил WinDbg, после чего запустил драйвер. Отладчик подключился к тестовой системе, WinDbg автоматически загрузил исходный код драйвера.

Установленный breakpoint

Установленный breakpoint

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

Отладка средствами Visual Studio

В новых версиях Visual Studio (начиная с 2013) также появилась возможность отладки драйверов. Кроме непосредственно отладчика Visual Studio предлагает широкие возможности по установке драйвера на удаленную систему, что позволяет производить отладку драйвера практически идентично отладке обычной программы (Сборка->расстановка точек останова->запуск отладки).

Для использования функций Visual Studio также необходимо обеспечить отладочное соединение с тестовой системой, в нашем случае это COM-порт, остальные действия не требуются (включать тестовый и отладочный режимы не нужно). Visual Studio позволяет автоматически настроить удаленную систему. Для этого на тестовую систему нужно установить пакет WDK Test Target Setup, который находится в директории %Program Files (x86)%Windows Kits10Remote%Платформа%. Этот .msi файл нужно скопировать на тестовую систему и установить.

Теперь пошагово сконфигурируем тестовую систему.

Шаг 1. Запустить Visual Studio.

Окно Visual Studio
Окно Visual Studio

Шаг 2. Открыть конфигуратор тестовых устройств.

Открыть конфигуратор тестовых устройств можно нажатием кнопки меню Extensions->Driver->Test->Configure Devices.

Запуск конфигуратора устройств

Запуск конфигуратора устройств

Шаг 3. Добавить и сконфигурировать тестовое устройство.

В первую очередь необходимо открыть окно конфигуратора нажатием кнопки Add New Device.

Окно конфигуратора устройств

Окно конфигуратора устройств

В окне ввести отображаемое имя тестовой системы, сетевое имя (можно ввести просто IP-адрес, либо включить сетевое обнаружение на тестовой системе), в Provisioning Options выбрать пункт Provision device and choose debugger settings, нажать Next.

Окно конфигуратора устройств

Окно конфигуратора устройств

В следующем окне раскрыть вкладку Windows Debugger — Kernel Mode и настроить опции:

  1. Connection Type: Serial

  2. Baud Rate: 115200

  3. Pipe: Checked (отметить)

  4. Reconnect: Checked (отметить)

  5. Pipe name: \.pipeWin10

  6. Target Port: com2 (или иной, должен совпадать с номером в настройках
    виртуальной машины)

Нажать Next.

Настройка отладчика

Настройка отладчика

Подождать выполнения настройки системы. В виртуальной машине вы можете наблюдать процессы создания нового пользователя, установку пакетов, выполнение скриптов. Это нормально. По окончании настройки виртуальная машина будет перегружена, а в Visual Studio появится сообщение об окончании настройки. В моем случае возникла одна ошибка при создании точки восстановления системы. Это можно проигнорировать. Нажать Finish.

Процесс настройки тестовой системы

Процесс настройки тестовой системы

Настройка тестовой системы почти закончена. На нее установлены средства TAEF — Test Authoring and Execution Framework и WDTF — Windows Driver Test Framework, позволяющие Visual Studio автоматически удалять старую версию драйвера, устанавливать новую, а также проводить автоматическое тестирование (вопрос автоматических тестов выходит за рамки данного материала).

ВНИМАНИЕ!!! В самом начале статьи я рекомендовал выяснить версию Windows на тестовой машине. Если она совпадает с версией установленного пакета WDK, то данный абзац можно не читать. WDK имеет обратную совместимость, то есть установленная WDK 1903 позволяет разрабатывать драйверы для предыдущих сборок (можно найти этот параметр в свойствах проекта, хотя я не сталкивался с ситуацией, когда драйвер не работает на некоторой сборке), однако пакет WDK — это не только набор заголовочных файлов, расширение для Visual Studio, но еще и набор вспомогательных утилит для отладки (тот же WinDbg) и тестирования. В том числе в пакет WDK входит и названный выше WDTF. И он обратной совместимости не имеет (или, возможно, не имеет для некоторых сборок). Для проверки наличия WDTF необходимо проверить на тестовой системе содержимое директории C:Program Files (x86)Windows Kits10TestingRuntimes. Если там содержатся поддиректории TAEF и WDTF, то все в порядке, а если только TAEF, как в моем случае, то нужно отдельно установить WDTF из пакета WDK версии, совпадающей с версией тестовой системы (напомню, у меня это Windows 10 1709). На тестовую систему из директории WDKInstallers необходимо скопировать файл Windows Driver Testing Framework (WDTF) Runtime Libraries соответствующей разрядности и попытаться установить его командой msiexec /i «Windows Driver Testing Framework ….». Установщик выдаст ошибку отсутсвия .cab файла. Найдите соответствующий файл в той же директории Installers, скопируйте на тестовую машину и повторите установку. Рядом с директорией TAEF должна появиться WDTF.

Тестовая система готова к загрузке и отладке драйвера. Visual Studio предлагает различные варианты установки (Deploy) драйвера на тестовую систему, настройки доступны в свойствах проекта во вкладке Driver Install->Deployment. В первую очередь нужно выбрать тестовую машину из выпадающего списка. Выше она уже была сконфигурирована и теперь доступна.

Настройки установки драйвера

Настройки установки драйвера

Подробно с различными вариантами можно ознакомиться на портале Microsoft. Мне показались наиболее понятными два из них: Install/Reinstall and Verify и Custom Command Line. Стоит отметить, что не совсем корректно работают точки остановки. Даже при их установке выполнение не прерывается. Нужно вставить как минимум одну конструкцию DbgBreakPoint(); (я это делаю первой же строкой функции DriverEntry), дальше отладку можно производить привычным для пользователя Visual Studio образом, пошаговая отладка нормально работает, установленные точки остановки тоже.

При опции Install/Reinstall and Verify драйвер будет установлен (переустановлен) и запущен, однако система будет перезагружена (это долго), а драйвер будет установлен с опцией старта при запуске системы. Для большинства случаев это не должно быть проблемой, однако если для вас важен момент запуска драйвера, то этот способ не подходит. Я устанавливаю конструкцию прерывания в первой строке DriverEntry, а также устанавливаю точку остановки на строке с выводом отладочного сообщения и возвратом из функции и нажимаю привычное F5.

Готовность к отладке

Готовность к отладке

На виртуальной машине можно увидеть исполнение скриптов. Также могут появляться сообщения об ошибках, однако даже с некоторыми ошибками все работает. В моем случае по неизвестным мне причинам установка драйвера не всегда удается с первого раза (в Visual Studio вы увидите сообщение о том, что программа завершила работу с ненулевым кодом). Но со второй-третьей попытки все начинает работать. После исполнения скриптом система перезагрузится, драйвер начнет загружаться, исполнение остановится на конструкции DbgBreakPoint();. Отладчик Visual Studio должен подключиться к виртуальной машине, отобразить в окне с исходным кодом текущую строку и нормальным образом реагировать на пошаговое исполнение, показывать значения переменных, отображать содержимое памяти, и, что важно, останавливаться на установленных средствами Visual Studio точках остановки.

Окно Debugger Immediate Window точно такое же, как и в WinDbg. Точнее говоря, это одно и то же. Поэтому Visual Studio через него поддерживает все команды WinDbg, а среди них много полезных.

Подключенный отладчик

Подключенный отладчик
Содержимое окон Locals и memory
Содержимое окон Locals и memory

Еще один способ установки драйвера, который я использую — это Custom Command Line. Можно создать простой bat-скрипт, содержащий команды по установке и запуску драйвера. Visual Stuio позволяет указать дополнительные файлы, которые нужно скопировать на тестовую систему, однако эта функция не работает. Поэтому создаем файл createandstart.bat на диске C, который содержит две строки: SC CREATE HelloWorldDriver binPath= C:DriverTestDriversHelloWorldDriver.sys type=kernel и SC START HelloWorldDriver

Скрипт установки и запуска

Скрипт установки и запуска

А в поле ввода под опцией Custom Command Line указать C:createandstart.bat

Настрока установки

Настрока установки

При нажатии F5 драйвер установится, запустится и Visual Studio укажет на строку с вызовом макроса DbgBreakPoint();

Простая отладка средствами Visual Studio

Однако все возможности Visual Studio Deployment раскрываются при создании тестов. Для простой отладки все это лишнее, поэтому, возможно, будет гораздо проще настроить тестовую систему для отладки самостоятельно (утилитой bcdedit), далее вручную запускать драйвер, а отлаживать его средствами Visual Studio. Такой подход представляет собой что-то среднее между рассмотренными выше. Для подготовки к отладке необходимо выполнить следующие шаги:

Шаг 1. Подготовить виртуальную машину.

На виртуальной машине нужно включить тестовый и отладочный режимы, а также установть драйвер командой SC CREATE.

Шаг 2. Сконфигурировать Visual Studio.

В Visual Studio открыть конфигуратор тестовых устройств, однако на первом шаге выбрать вариант Manual configure debuggers and do not provision, нажать Next, в следующем окне настроить все идентично, как на рисунке.

Ручная настройка

Ручная настройка
Настройка отладчика
Настройка отладчика

Теперь на тестовой системе можно запустить драйвер командой SC START. Выполнение драйвера остановится на строке DbgBreakPoint();, а виртуальная машина будет ожидать подключения отладчика. В Visual Studio нужно нажать Debug->Attach To Process, в появившемся окне в поле Connection type выбрать Windows Kernel Mode Debugger, в поле Connection target — имя настроенной выше тестовой машины, нажать Attach.

Подключение отладчика к процессу

Подключение отладчика к процессу

Очень вероятно, что вы получите ошибку Frame is not in module:

Несоответствие драйвера исходному коду

Несоответствие драйвера исходному коду

Введите в поле ввода окна Debugger Immediate Window команду .reload и переключитесь на файл с исходным кодом. Если и это не помогло, скорее всего, вы что-то изменили в исходном коде, скомпилировали, но забыли скопировать новую версию драйвера. Пересоберите (для надежности) проект, скопируйте его на тестовую машину, запустите драйвер, подключие отладчик снова.

Я считаю этот способ самым удобным при отладке драйвера. Он позволяет использовать более комфортную и привычную Visual Studio, при этом не тратить целые минуты на установку новой версии драйвера на тестовую систему.

Заключение

Разработка драйверов для ОС Windows — достаточно увлекательный процесс. Реализация даже мелких и простых драйверов позволяет глубже понять внутреннее устройство Windows, что весьма полезно. Однако начинающих системных программистов отпугивает не столько сложность написания непосредственно кода (как минимум, есть множество примеров), сколько сложность установки и отладки. Надеюсь, что данный материал поможет кому-то не потерять интерес в первом же проекте.

Upd

В комментариях были выражены опасения, что инструкция по установке драйвера некорректная в части отключения подписи драйверов. В результате эксперимента установлено, что все нормально и работает ровно так, как описано. Также попутно выяснилось, что можно смело качать последнюю версию WDK (для 22H2) и SDK (если у вас Windows 10, а не Windows 11) и тогда разработку можно вести в Visual Studio 2022.

Download the Windows Driver Kit (WDK)

The WDK is used to develop, test, and deploy Windows drivers.

Runtime requirements

You can run the Windows 10, version 2004 WDK on Windows 7 and later, and use it to develop drivers for these operating systems:

Client OS Server OS
Windows 10 Windows Server 2019, Windows Server 2016
Windows 8.1 Windows Server 2012 R2
Windows 8 Windows Server 2012
Windows 7 Windows Server 2008 R2 SP1

WDK for Windows 10, version 2004

Step 1: Install Visual Studio 2019

The WDK requires Visual Studio. For more information about system requirements for Visual Studio, see Visual Studio 2019 System Requirements.

The following editions of Visual Studio 2019 support driver development for this release:

When you install Visual Studio 2019, select the Desktop development with C++ workload. The Windows 10 Software Development Kit (SDK) is automatically included, and is displayed in the right-hand Summary pane. Note that the version of the SDK that is compatible with the WDK for Windows 10, version 2004 may not be the default SDK. To select the correct SDK:

In Visual Studio Installer, on the Individual components tab, search for Windows 10 SDK (10.0.19041.0), select this version and continue with install. Note that Visual Studio will automatically install Windows 10 SDK (10.0.19041.1) on your machine.

If you already have Visual Studio 2019 installed, you can install the Windows 10 SDK (10.0.19041.1) by using the Modify button in Visual Studio install.

WDK has Spectre mitigation enabled by default but requires spectre mitigated libraries to be installed with Visual Studio for each architecture you are developing for. Additionally, developing drivers for ARM/ARM64 require the build tools for these architectures to also be installed with Visual Studio. To locate these items you will need to know the latest version of MSVC installed on your system.

To find the latest version of MSVC installed on your system, in Visual Studio Installer go to workload page, on the right pane under installation details, expand Desktop development with C++ and locate the MSVC v142 — VS 2019 C++ x64/x86 build tools (V14.xx) — note where xx should be the highest version available.

With this information (v14.xx), go to Individual components and search for v14.xx. This will return the tool sets for all architectures, including Spectre mitigated libs. Select the driver architecture you are developing for.

For example, searching for v14.25 returns the following:

Step 2: Install WDK for Windows 10, version 2004

The WDK Visual Studio extension is included in the default WDK installation.

Enterprise WDK (EWDK) for Windows 10, version 2004

The EWDK is a standalone, self-contained command-line environment for building drivers. It includes the Visual Studio Build Tools, the SDK, and the WDK. The latest public version of the EWDK contains Visual Studio 2019 Build Tools 16.3.0 and MSVC toolset v14.23. To get started, mount the ISO and run LaunchBuildEnv.

The EWDK also requires the .NET Framework version 4.7.2. For more information about other requirements for the .NET Framework, see .NET Framework system requirements.

EWDK with Visual Studio Build Tools

Driver samples for Windows 10

To download the driver samples, do one of the following:

  • Go to the driver samples page on GitHub, click Clone or download, and then click Download ZIP.
  • Download the GitHub Extension for Visual Studio, and then connect to the GitHub repositories.
  • Browse the driver samples on the Microsoft Samples portal.

Источник

Driver Development Tools

Purpose

The Windows Driver Kit (WDK) provides a set of tools that you can use to develop, analyze, build, install, and test your driver. The WDK includes powerful verification tools that are designed to help you detect, analyze, and correct errors in driver code during the development process. Many of these tools can be used very early in the development process where they are most critical and can save you the most time and effort.

Overview

The Windows Driver Kit (WDK) is fully integrated with Microsoft Visual Studio 2015. The WDK uses the same compiler and build tools that you use to build Visual Studio projects. The code analysis and verification tools can now be easily configured and launched from the Visual Studio development environment, so that you can find and fix problems in your driver source early in the development cycle.

The WDK provides a sophisticated driver test framework and a set of device fundamental tests that you can use to automatically build, deploy, and test your driver on remote test systems. The WDK provides the tools to make testing and debugging drivers more convenient and effective than before.

Driver Development Tools Documentation

This section describes the tools and techniques that can help you during development:

Resources

Universal Windows drivers allow developers to create a single driver that runs across multiple different device types, from embedded systems to tablets and desktop PCs. Hardware developers can use their existing components and device drivers across different form factors.

You can convert projects and solutions that you created with WDK 8 or Windows Driver Kit (WDK) 8.1 to work with Windows Driver Kit (WDK) 10 and Visual Studio 2015. Before you open the projects or solutions, run the ProjectUpgradeTool. The ProjectUpgradeTool converts the projects and solutions so that they can be built using WDK for Windows 10.

You can use the ApiValidator.exe tool to verify that the APIs that your driver calls are valid for a Universal Windows driver. The tool returns an error if your driver calls an API that is outside the set of valid APIs for Universal Windows drivers. This tool is part of the WDK for Windows 10.

More information and tips for driver developers about using the WDK and the Visual Studio build environment.

For specific information about building drivers, and using the verification tools and tests in the Visual Studio development environment.

Источник

Installing preview versions of the Windows Driver Kit (WDK)

This page contains installation instructions for Insider Preview (pre-release) versions of the Windows Driver Kit (WDK). The download links for the latest pre-release version of the WDK and the EWDK are on https://www.microsoft.com/software-download/windowsinsiderpreviewWDK.

For info about the latest released versions of the WDK, see Download the Windows Driver Kit (WDK). For downloads of earlier versions of the WDK, see Other WDK downloads.

Install Windows Driver Kit (WDK) Insider Preview

1. Install Visual Studio

  • The WDK now supports Visual Studio 2019. All editions are supported. The WDK no longer supports Visual Studio 2017.
  • Download from https://visualstudio.microsoft.com/vs/preview/.
  • Select workload: Development with C++.
  • ARM: To build ARM drivers you must additionally install the component: Individual components -> Compilers, build tools, and runtimes -> Visual C++ compilers and libraries for ARM.
  • ARM64: Currently not supported.

2. Disable strong name validation

The WDK Visual Studio Extensions are currently not strong name signed. Run the following commands from an elevated command prompt to disable strong name validation:

3. Install SDK Insider Preview

4. Install WDK Insider Preview

During installation you will see the Visual Studio installer install the WDK Visual Studio Extensions.

Install Enterprise WDK (EWDK) Insider Preview

The EWDK is a standalone self-contained command-line environment for building drivers. It includes Build Tools for Visual Studio 2019, the SDK, the WDK and support for ARM64 driver development. See more at Installing the Enterprise WDK.

To get started mount the ISO and select LaunchBuildEnv.

Run-time requirements for the WDK and the EWDK

The WDK requires Visual Studio. For more info about system requirements for Visual Studio, see Visual Studio 2019 System Requirements.

In addition, the EWDK requires .NET 4.7.2. For more info about what .NET runs on, see .NET Framework system requirements.

You can use the WDK Insider Preview and the EWDK Insider Preview to develop drivers for these operating systems:

Источник

What Is Windows Driver Kit

What is Windows Driver Kit? It is a fully integrated driver development system, which includes a Windows Driver Device Kit, used to test the reliability and stability of Windows drivers. If you want to get more information about Windows, you can go to the MiniTool official website.

History of Windows Driver Kit

Previously, the Windows Driver Kit was called the Windows Driver Development Kit and supported the development of the Windows Driver Model.

When Microsoft released Windows Vista and added the following previously separated tools to the toolkit, it had the current name: Installable File System Toolkit (IFS Toolkit), Driver Test Manager (DTM), although DTM subsequently Was renamed and removed from the WDK again.

Windows 2000 and earlier versions of the DDK do not include a compiler; instead, you need to install Visual C++ separately to compile the driver. Starting from the Windows XP version, the DDK and later versions of the Windows Driver Kit include a command-line compiler for compiling drivers.

One of the reasons given by Microsoft to include the compiler is that if you use the same compiler version as Windows itself to compile, and Visual C++ is aimed at application development and has a different product cycle, you can improve the quality of the driver.

Change more frequently. Windows Driver Kit 8.x and later versions go back to requiring the installation of a matching version of Visual Studio respectively, but this time the integration is more complete, and you can directly edit/build/debug the driver in Visual Studio.

System Requirements of Windows Driver Kit

You can run the Windows 10, version 2004 WDK on Windows 7 and later, and use it to develop drivers for these operating systems:

Client OS

  • Windows 10     
  • Windows 8.1
  • Windows 8       
  • Windows 7

Server OS

  • Windows Server 2019
  • Windows Server 2016
  • Windows Server 2012 R2
  • Windows Server 2012
  • Windows Server 2008 R2 SP1

How to Download & Install Windows Driver Kit

Now, let’s see how to download & install Windows Driver Kit on Windows 10.

Step 1: Install Visual Studio 2019

Windows Driver Kit requires Visual Studio. When installing Visual Studio 2019, choose desktop development with a C++ workload. The Windows 10 Software Development Kit (SDK) will be automatically included and displayed in the Summary pane on the right.

Please note that the SDK that is compatible with the Windows 10 WDK may not be the default SDK. To choose the correct SDK, do the following:

On the Single Component tab of Visual Studio Installer, search for Windows 10 SDK (10.0.19041.0), select this version and continue the installation. Please note that Visual Studio will automatically install the Windows 10 SDK (10.0.19041.1) on your computer.

If you have already installed Visual Studio 2019, you can use the Modify button in the Visual Studio installation to install the Windows 10 SDK (10.0.19041.1).

The WDK has the Spectre mitigation feature enabled by default, but the Spectre mitigation library needs to be installed for each architecture to be developed for Visual Studio. In addition, developing drivers for ARM/ARM64 also requires that the build tools for these architectures can also be installed with Visual Studio. To find these items, you will need to know the latest version of MSVC installed on your system.

To find the latest version of MSVC installed on your system, go to the workload page in the Visual Studio installer, in the right pane under the installation details, expand Desktop Development with C++ and find MSVC v142-VS 2019 C++ x64/x86 build tools (V14.xx)-Please note that xx should be the highest version available.

With this information (v14.xx), go to the various parts and search for v14.xx. This will return the toolset for all architectures, including the Spectre mitigation library. Select the driver architecture to be developed.

Step 2: Install the updated Windows SDK for Windows 10

Step 3: Install Refreshed WDK for Windows 10

Final Words

To sum up, here is all the information on Windows Driver Kit. You can know what it is and the Windows Driver Kit download. Besides, you can find the steps of installing it on Windows 10.

У нас Windows 10-64.

Задача разработать например драйвер устройства под Windows.
Устанавливаем Windows Device Driver Kit 7 :
Скачиваем с офф.сайта microsoft ISO, разархивируем , запустим KitSetup.exe

фотка 1

так выглядят в Панель управленияПрограммыПрограммы и компоненты

фотка 2

установлен у меня в C:WinDDK7600.16385.1

В C:WinDDK7600.16385.1src много примеров исходных кодов.
Примечание : если у вас уже установлен Win Driver Kit 10 , то придется удалить.

Фишка в том , что сборку надо запускать через запуск сначала командного файла (который устанавливает переменные среды) :
см. Пуск->Windows Driver

фотка 3

открывается консоль, где и надо ввести build (в каталоге вашего проекта). Процесс сборки выглядит примерно так:

фотка 4

для x64 входим через C:WindowsSystem32cmd.exe /k C:WinDDK7600.16385.1binsetenv.bat C:WinDDK7600.16385.1 fre x32-64

Windows 10 — надо сначала отключить проверку цифровой подписи (у меня срабатывает при нажатой SHIFT + клик Перезагрузка)
Отключаем.

фотка 5

Далее просто пробуем написать простейший kernel драйвер

На самом деле в дальнейшем в этой ветке сайта мы будем заниматься UMDF драйверами, но для проверки первого драйвера подвернулся пример driver.sys (kernel драйвер, драйвер уровня ядра)

Компилируем простейший драйвер (sys — кернел драйвер)


#include <wdm.h>
 
static
VOID Unload(DRIVER_OBJECT * pDriverObj)
{
	DbgPrint("...........Unloadn");
}
 
NTSTATUS DriverEntry(DRIVER_OBJECT * pDriverObj, UNICODE_STRING * pRegPath)
{
	DbgPrint("DriverEntry................n");
    return STATUS_SUCCESS;
}

Для варианта сборки x86 пробуем зарегистрировать драйвер

фотка 6

Для варианта сборки amd64 получаем

фотка 7

Теперь по другому пробуем проверить запущен ли все-таки драйвер через программу OSR Driver Loader:

фотка 8

Получается драйвер все-таки запускается несмотря на ругань по поводу сертификата.

смотрим например еще так :


C:WINDOWSsystem32>sc query mydriver

Имя_службы: mydriver
        Тип                : 1  KERNEL_DRIVER
        Состояние          : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        Код_выхода_Win32   : 0  (0x0)
        Код_выхода_службы  : 0  (0x0)
        Контрольная_точка  : 0x0
        Ожидание           : 0x0

osr driver loader — прекрасно и сама регистрирует / запускает / останавливает / удаляет драйвер. Только не забывайте перезагружаться.

Отладка

У нас на сайте см. отдельный раздел по отладке драйверов.

Понравилась статья? Поделить с друзьями:
  • Windows driver android phone windows 7
  • Windows drive fitness test официальный сайт
  • Windows drive fitness test windft скачать бесплатно на русском
  • Windows dreamscenes enabler для windows 7 скачать бесплатно
  • Windows dreamscene скачать с официального сайта