Меню Закрыть

Microsoft kernel mode driver framework windows 10

Содержание

This topic summarizes the new features and improvements for Windows Driver Frameworks (WDF) drivers in WindowsВ 10.

WindowsВ 10, version 1903 (March 2019 Update, 19H1) includes Kernel-Mode Driver Framework (KMDF) version 1.29 and User-Mode Driver Framework (UMDF) version 2.29.

You can use these framework versions to build drivers for:

  • WindowsВ 10 (all SKUs)
  • Windows Server, version 1809

For version history, see KMDF Version History and UMDF Version History. Except where noted, UMDF references on this page describe version 2 functionality that is not available in UMDF version 1.

New in WDF for Windows 10, version 1903

No functionality added or changed.

New in WDF for Windows 10, version 1809

  • Added new API WdfDriverRetrieveDriverDataDirectoryString

New in WDF for Windows 10, version 1803

New in WDF for Windows 10, version 1709

New in WDF for Windows 10, version 1703

In Windows 10, version 1703, WDF includes the following enhancements:

New WDF Verifier settings to detect excessive object creation

In some cases, framework objects are incorrectly parented and not deleted after use. With this feature, you can specify a maximum number of objects and what should happen when this threshold is exceeded.

To start monitoring, add the following registry values under: HKEY_LOCAL_MACHINESystemCurrentControlSetServices Parameterswdf

Add a DWORD value named ObjectLeakDetectionLimit with the threshold value. This is the maximum number of objects of the types described in the ObjectsForLeakDetection key.

Add a new REG_MULTI_SZ value named ObjectsForLeakDetection that lists each type name to verify. For example, you could specify WDFDMATRANSACTION WDFDEVICE . To specify all handle types, use * as the string.

To control whether exceeding this threshold should cause a debug break or a bugcheck, set the DbgBreakOnError key.

By default, if the ObjectsForLeakDetection key is not specified, the framework monitors WDFREQUEST, WDFWORKITEM, WDFKEY, WDFSTRING, WDFOBJECT, and WDFDEVICE.

The limit scales with the number of devices installed, so if the driver creates three WDFDEVICE objects, the WDF Verifier limit is three times the value specified in ObjectLeakDetectionLimit.

If you specify WDFREQUEST, the verifier only counts WDFREQUEST objects that the driver creates.

This feature does not currently support tracking the WDFMEMORY object type.

SleepStudy tool provides info on KMDF drivers

The SleepStudy software tool reports the number of power references that a KMDF driver has that are preventing the system from going to sleep. For more info, see Modern standby SleepStudy.

The rest of this page describes functionality that was added in Windows 10, version 1507.

WDF source code is publicly available

The WDF source code is now available as open source on GitHub. This is the same source code from which the WDF runtime library that ships in WindowsВ 10 is built. You can debug your driver more effectively when you can follow the interactions between the driver and WDF. Download it from https://github.com/Microsoft/Windows-Driver-Frameworks.

The private symbol files for WDF on WindowsВ 10 are now available through the Microsoft Symbol Server.

The Windows Driver Kit (WDK)В 10 samples are also now published to GitHub. Download them from https://github.com/Microsoft/Windows-Driver-Samples.

Automatic Source Level Debugging of Framework Code

When you use WinDbg to debug a WDF driver on WindowsВ 10, WinDbg automatically retrieves the framework source code from Microsoft’s public GitHub repository. You can use this feature to step through the WDF source code while debugging, and to learn about framework internals without downloading the source code to a local machine. For more information, see New support for source-level debugging of WDF code in Windows 10, Debugging with WDF Source, and Video: Debugging your driver with WDF source code.

Читайте также:  Почему не любят windows 10

Universal Driver Compliance

All WDF driver samples and Visual Studio driver templates are Universal Windows driver compliant.

All KMDF and UMDF 2 functionality is Universal Windows driver compliant.

Note that UMDF 1 drivers run only on WindowsВ 10 for desktop editions and earlier versions of desktop Windows. Want to benefit from the universal capabilities of UMDF 2? To learn how to port your old UMDF 1 driver, see Porting a Driver from UMDF 1 to UMDF 2.

Debugging and Diagnosability

All KMDF and UMDF 2 drivers can use an always on, always available Inflight Trace Recorder (IFR). When a driver provides a custom trace, the driver IFR log contains the trace messages. Note that the new driver IFR log is separate from the framework IFR log that WDF creates for each driver.

The IFR maintains a circular buffer of WPP traces in non-pageable memory. If a driver crashes, the logs are frequently included in the crash dump file.

If you turn on the IFR in your driver binary, the IFR is present and running during the lifetime of your driver. You don’t need to start an explicit trace collection session.

IFR logs are included in minidump files except when the responsible driver is undetermined or if the crash was a host timeout.

If you have a debugger connected, you can access both the driver and framework IFR logs by issuing !wdfkd.wdflogdump.

If you do not have a debugger connected, you can still access both logs. To learn how, see Video: Accessing driver IFR logs without a debugger.

When debugging a UMDF driver, you can merge framework logs with driver logs by issuing: !wdfkd.wdflogdump -m

UMDF logs (WudfTrace.etl) and dumps are now located in %ProgramData%MicrosoftWDF instead of %systemDrive%LogFilesWudf.

New debugger command: !wdfkd.wdfumtriage provides a kernel-centric view of all UMDF devices on the system.

You can run !analyze to investigate UMDF verifier failures or UMDF unhandled exceptions. This works for live kernel debugging as well as debugging user crash dump files from %ProgramData%MicrosoftWDF.

In KMDF and UMDF 2, you can monitor power reference usage in the debugger. For info, see Debugging Power Reference Leaks in WDF.

You can use !wdfkd.wdfcrashdump to display error information about UMDF 2 drivers. For more information, see !wdfkd.wdfcrashdump.

Performance Tracing tool for WDF drivers

You can use the Windows Performance Toolkit (WPT) to view performance data for a given KMDF or UMDF 2 driver. When tracing is enabled, the framework generates ETW events for I/O, PnP, and Power callback paths. You can then view graphs in the Windows Performance Analyzer (WPA) that show I/O throughput rates, CPU utilization, and callback performance. The WPT is included in the Windows Assessment and Deployment Kit (ADK).

Additional support for HID drivers in UMDF

UMDF now fully supports HID filters (enumerated by HIDClass) and minidrivers. Simply port your existing KMDF driver or write a new UMDF 2 filter; the functionality is automatically enabled.

UMDF HID minidrivers that are enumerated by ACPI can perform selective suspend. For more information, see Creating WDF HID Minidrivers.

UMDF drivers can now be installed in the HID stack for low latency input devices such as touch and mouse. A driver for an input device should specify the UmdfHostPriority INF directive. For information, see Specifying WDF Directives in INF Files.

Support for interrupts for GPIO-backed devices

  • UMDF 2 supports interrupts for GPIO-backed devices like hardware push-buttons. KMDF supports these devices natively, without the workaround described in Handling Active-Both Interrupts. For more information, see Creating an Interrupt Object.
Читайте также:  Intel core i5 2400 3 10 ghz

UMDF no longer requires WinUSB

New support has been added for USB drivers in UMDF. A UMDF 2 USB driver no longer uses WinUSB. To use the new functionality, the driver sets the UmdfDispatcher directive to NativeUSB, instead of WinUSB. See Specifying WDF Directives in INF Files.

Improved Performance

UMDF system components consume less disk space.

KMDF and UMDF drivers use less non-paged memory.

Improved framework version checking reduces header/library mismatches.

UMDF provides improved buffer mapping for HID transfers.

Kernel Mode Driver Framework Runtime by Microsoft Corporation.

This service also exists in Windows 7, 8 and Vista.

Startup Type

Windows 10 version Home Pro Education Enterprise
1507 Boot Boot Boot Boot
1511 Boot Boot Boot Boot
1607 Boot Boot Boot Boot
1703 Boot Boot Boot Boot
1709 Boot Boot Boot Boot
1803 Boot Boot Boot Boot
1809 Boot Boot Boot Boot
1903 Boot Boot Boot Boot
1909 Boot Boot Boot Boot

Default Properties

Display name: Kernel Mode Driver Frameworks service
Service name: Wdf01000
Type: kernel
Path: %WinDir%system32driversWdf01000.sys
Error control: normal
Group: WdfLoadGroup

Default Behavior

The Kernel Mode Driver Frameworks service is a kernel mode driver. If Kernel Mode Driver Frameworks service fails to start, the error is logged. Windows 10 startup proceeds, but a message box is displayed informing you that the Wdf01000 service has failed to start.

Restore Default Startup Type for Kernel Mode Driver Frameworks service

Automated Restore

1. Select your Windows 10 edition and release, and then click on the Download button below.

2. Save the RestoreKernelModeDriverFrameworksserviceWindows10.bat file to any folder on your hard drive.

3. Right-click the downloaded batch file and select Run as administrator.

4. Restart the computer to save changes.

Note. Make sure that the Wdf01000.sys file exists in the %WinDir%system32drivers folder. If this file is missing you can try to restore it from your Windows 10 installation media.

Содержание статьи

Процессорные архитектуры x86 и x64 имеют четыре кольца защиты, из которых в Windows по факту используются всего два — это ring 3 (режим пользователя) и ring 0 (режим ядра). Бытует мнение, что код режима ядра — самый привилегированный и «ниже» ничего нет. На самом деле архитектура x86/x64 позволяет опускаться еще ниже: это технология виртуализации (hypervisor mode), которая считается кольцом −1 (ring −1), и режим системного управления (System Management Mode, SMM), считающийся кольцом −2 (ring −2), которому доступна память режима ядра и гипервизора.

Итак, мы решили писать собственный драйвер. Начнем с выбора инструментария. Я советую использовать Microsoft Visual Studio, как наиболее user-friendly IDE. Также необходимо будет установить Windows SDK и Windows Driver Kit (WDK) для твоей версии ОС. Кроме того, я крайне рекомендую запастись такими утилитами, как DebugView (просмотр отладочного вывода), DriverView (позволяет получить список всех установленных драйверов) и KmdManager (удобный загрузчик драйверов).

Драйверы в Windows начиная с Vista могут быть как режима пользователя (User-Mode Driver Framework, UMDF), так и режима ядра (Kernel-Mode Driver Framework, KMDF). Более ранние драйверы Windows Driver Model (WDM) появились в Windows 98 и сейчас считаются устаревшими.

Драйверы UMDF имеют намного более ограниченные права, чем KMDF, однако они используются, например, для управления устройствами, подключенными по USB. Помимо ограничений, у них есть очевидные плюсы: их намного проще отлаживать, а ошибка в их написании не вызовет глобальный системный сбой и синий экран смерти. Такие драйверы имеют расширение dll.

Читайте также:  Flow exe что это

Что до драйверов режима ядра (KMDF), то им дозволено куда больше, а расширение файлов, закрепленное за ними, — это sys. В этой статье мы научимся писать простые драйверы режима ядра, напишем драйвер для скрытия процессов методом DKOM (Direct Kernel Object Manipulation) и его загрузчик.

Создание драйвера KMDF

После того как ты создашь проект драйвера, Visual Studio автоматически настроит некоторые параметры. Проект будет компилироваться в бинарный файл в соответствии с тем, какая выбрана подсистема. Наш вариант — это NATIVE, подсистема низкого уровня, как раз для того, чтобы писать драйверы.

Точка входа в драйвер

Строго говоря, точка входа в драйвер может быть любой — мы можем сами ее определить, добавив к параметрам компоновки проекта -entry:[DriverEntry] , где [DriverEntry] — название функции, которую мы хотим сделать стартовой. Если в обычных приложениях основная функция обычно называется main, то в драйверах точку входа принято называть DriverEntry.

Выглядеть это будет так:

Давай пройдемся по параметрам, которые передаются DriverEntry . pDriverObject имеет тип PDRIVER_OBJECT , это значит, что это указатель на структуру DRIVER_OBJECT , которая содержит информацию о нашем драйвере. Мы можем менять некоторые поля этой структуры, тем самым меняя свойства драйвера. Второй параметр имеет тип PUNICODE_STRING , который означает указатель на строку типа UNICODE . Она, в свою очередь, указывает, где в системном реестре хранится информация о нашем драйвере.

WARNING

Любая ошибка в драйвере может вызвать общесистемный сбой и BSOD. Вероятна потеря данных и повреждение системы. Все эксперименты я рекомендую проводить в виртуальной машине.

Interrupt Request Level (IRQL)

IRQL — это своеобразный «приоритет» для драйверов. Чем выше IRQL, тем меньшее число других драйверов будут прерывать выполнение нашего кода. Существует несколько уровней IRQL: Passive, APC, Dispatch и DIRQL. Если открыть документацию MSDN по функциям WinAPI, то можно увидеть примечания, которые регламентируют уровень IRQL, который требуется для обращения к каждой функции. Чем выше этот уровень, тем меньше WinAPI нам доступно для использования. Первые три уровня IRQL используются для синхронизации программных частей ОС, уровень DIRQL считается аппаратным и самым высоким по сравнению с программными уровнями.

Пакеты запроса ввода-вывода (Input/Output Request Packet)

IRP — это запросы, которые поступают к драйверу. Именно при помощи IRP один драйвер может «попросить» сделать что-то другой драйвер либо получить запрос от программы, которая им управляет. IRP используются диспетчером ввода-вывода ОС. Чтобы научить программу воспринимать наши IRP, мы должны зарегистрировать функцию обратного вызова и настроить на нее массив указателей на функции. Код весьма прост:

А вот код функции-заглушки, которая всегда возвращает статусный код STATUS_SUCCESS . В этой функции мы обрабатываем запрос IRP.

Теперь любой запрос к нашему драйверу вызовет функцию-заглушку, которая всегда возвращает STATUS_SUCCESS . Но что, если нам нужно попросить драйвер сделать что-то конкретное, например вызвать определенную функцию? Для этого регистрируем управляющую процедуру:

Здесь мы объявили процедуру с именем IRP_MY_FUNC и ее кодом — 0x801 . Чтобы драйвер ее обработал, мы должны настроить на нее ссылку, создав таким образом дополнительную точку входа в драйвер:

После этого нам нужно получить указатель на стек IRP, который мы будем обрабатывать. Это делается при помощи функции IoGetCurrentIrpStackLocation , на вход которой подается указатель на пакет. Кроме этого, необходимо будет получить от диспетчера ввода-вывода размеры буферов ввода-вывода, чтобы иметь возможность передавать и получать данные от пользовательского приложения. Шаблонный код каркаса обработчика управляющей процедуры:

Продолжение доступно только участникам

Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте

Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score! Подробнее

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.