Windows drivers visual studio

How to test a driver at runtime using Visual Studio

The WDK extensions to Visual Studio provide a device testing interface that enables you to conveniently build, deploy, install, and test a driver on a test computer on your network. The WDK provides a collection of device driver tests that you can use to test the features and functions of your driver.

Prerequisites

  • A Driver Package that is ready to install. You must first create and build your driver and then create a Driver Package for installation. For more information, see Building a Driver and Creating a Driver Package.
  • The driver must be test signed. For more information, see Signing a Driver.
  • A test computer (or computers). The test computer must be on the same network as the computer that you are using for development. Both computers must be connected to the same domain, or both connected to the network under the same workgroup. The test computer should be running the version of Windows that you want to target for testing.
  • A device to be tested.
  • (Recommended) Set up a kernel mode debugging connection to the test computer. To use a network connection for kernel mode debugging, the target computer must be running WindowsВ 8. On computers running Windows 7 or Windows Vista, you can set up a USB, 1394, or a serial connection for kernel mode debugging. For more information, see Provision a computer for driver deployment and testing (WDK 8.1).

Instructions

Step 1: Configure computers for testing

From Visual Studio, you can configure and provision computers for testing. When you configure the test computers, the WDK driver test framework automatically enables the test computer for remote debugging and transfers the necessary test binaries and support files.

  1. If you have not already done so, follow the instructions to Provision a computer for driver deployment and testing (WDK 8.1).
  2. Connect the device that you want to test to the test computer or computers.

After you have configured and provisioned a test computer, you can use Visual Studio to deploy drivers, schedule tests, and debug drivers on the test computer. For information about deployment and about how you can deploy a driver automatically at build time, see Deploying a Driver to a Test Computer.

You can also enable and set options for Driver Verifier, the runtime verification tool for drivers. Driver Verifier monitors your driver as you run tests on the test computer. For information about setting the Driver Verifier options for deployment, see Driver Verifier Properties for Driver Projects.

You can also run tests outside of Visual Studio, for more information see How to test a driver at runtime from a Command Prompt. Starting in WDK 8.1, you can copy and run the HCK Test Suites on test computers using command scripts. See How to run the HCK Test Suites in WDK 8.1.

Step 2: Select an HCK Test Suite to run on the test computer (using WDK 8.1)

Starting with WDK 8.1, you can select HCK Test Suites to run on the test computer. The HCK Test Suites include the Device Fundamentals Tests, and Windows Hardware Certification kit (HCK) Basic tests for graphics, imaging, wireless LAN, mobile broadband (CDMA and GSM), and WiFi Direct devices.

Step 3: Select the tests to run on the test computer (WDK 8 and WDK 8.1)

To make driver testing on different test targets easier, tests are scheduled to run against test systems in units called test groups. A driver test group is a collection of tests that you select to run on the test computer. The driver test groups help you organize your tests and test results from each test pass. You can save your test results to separate folders. You can create and manage test groups, change parameters passed to the tests in the test groups, and schedule them to run against your test systems.

From the Driver menu, select Test and then select Test Group Explorer.

In the Driver Test Group Explorer window, select the Create a new test group button. Or, select New Test Group from the Driver menu.

In the Driver Test Group window for the group that you created, type a name in Test Group Name text box to identify the group. The default name is Driver Test Group_nnnnn, where nnnnn represents the number of the test group

Select Add/Remove Tests.

In the Add or Remove Driver Tests dialog box, you can specify the driver test category and architecture (All, x86, x64, ARM). By default all tests are shown. To view the test categories, select the folders in the Driver Test Categories drop-down list.

For example, in WDK 8, to select all of the Device Fundamentals tests that are used in the Windows Hardware Certification Kit (HCK), select All Tests, Certification, and Device Fundamentals. For information about the tests, see How to select and configure the Device Fundamentals Tests.

In WDK 8.1, the Device Fundamentals tests are under All Tests, HCK Tests, Certification, and Device Fundamentals folder. In WDK 8.1 the Driver Test Categories include the HCK (Basic) Tests. See How to run the HCK Test Suites in WDK 8.1 for more information.

Be sure that you select the tests that match the architecture of the intended test computer (x86, x64, ARM). Use the Architecture Filter to show only those tests that will run on your test computer.

Читайте также:  Windows docker shared drives

Select >> to add the selected tests.

Step 4: Configure test parameters

After you select the tests for your test group, you can configure any of the runtime parameters that are passed to the driver tests. For example, many of the Device Fundamentals Tests have a parameter DQ, which stands for Device Query. This is a Simple Data Evaluation Language (SDEL) query. The Windows Driver Test Framework provides SDEL as a query language to simplify the task of collecting targets based on attributes or relationships.

For example, to run the tests for USB devices only, use the device query: . You can change the value of each test parameter in the test group.

You can view and edit the all of the runtime test parameters for a test by selecting on the name of the test in the Driver Test Group window. The Driver Test Group window provides a description of the selected test and also provides a description of the test parameters that you select. For information about setting the test parameters, see How to select and configure the Device Fundamentals Tests

After you select the tests, set the parameters, and name the group, select Save.

When you save the test group, the test group will become the currently selected test group, and the name of the test group will appear in the Driver Test toolbar. You can now run tests against the currently selected remote test computer (also shown in the Driver Test toolbar).

Step 5: Build and deploy the driver

  • From the Build menu, select Deploy Solution.

For information about deploying a driver automatically at build time, see Deploying a Driver to a Test Computer. For information about automatically setting the Driver Verifier options on the test computer, see Driver Verifier Properties for Driver Projects. You should always enable Driver Verifier on your test computer.

Step 6: Run the tests on the test computer

  • From the Driver menu, select Test > Run test. By default, the Run test command runs all of the tests in the currently selected test group.

Remarks

For information about the driver tests and test categories, see How to select and configure the Device Fundamentals Tests. For information about the testing framework, see Test Authoring and Execution Framework (TAEF) and Windows Driver Test Framework (WDTF).

You can write your own driver tests and deploy those tests on test computers. For more information, see How to write a driver test.

Running the Device Fundamentals tests in Visual Studio early in the development cycle will help you when are finally ready to test your driver using the Windows Hardware Certification Kit (HCK).

Развертывание драйверов Driver deployment

Развертывание драйвера в Windows 10 IoT базовая с помощью Visual Studio. Deploy a driver on Windows 10 IoT Core with Visual Studio.

Настройте проект драйвера Visual Studio, чтобы можно было компилировать и развертывать драйвер для определенной платформы на этапе разработки драйвера. Configure your Visual Studio driver project so that you can compile and deploy a driver for a specific platform during driver development phase.

В этом упражнении вы можете использовать образец драйвера гпиокмдфдемо. For this exercise you can use the gpiokmdfdemo sample driver.

Если вы хотите добавить драйвер к образу, ознакомьтесь с инструкциями в нашем производственном руководством IOT. If you’re looking to add a driver to an image, please visit the instructions in our IoT Manufacturing Guide.

Шаг 1. Настройка Step 1: Setup

На устройстве On the device

  • Убедитесь, что на устройстве установлен образ Иоткоре, следуя инструкциям в разделе Приступая к работе. Make sure that your device has an IoTCore image installed by following the Get Started instructions.
  • Подключитесь к устройству с помощью PowerShell. Connect to your device via PowerShell.

На компьютере On the PC

Убедитесь, что установлен Visual Studio 2017. Make sure you have installed Visual Studio 2017.

Установите набор драйверов для Windows. Install the Windows Driver Kit. Вам потребуется установить пакет SDK и WDK. You will need to install the SDK and WDK.

Установите сертификаты, чтобы правильно подписать драйвер и запустить его на устройстве. Install the certificates so that the driver is signed correctly and can run on your device. В командной строке с повышенными привилегиями выполните команды, перечисленные ниже. From an elevated command prompt execute the commands listed below:

  1. cd c:\Program Files (x86)\Windows Kits\10\Tools\bin\i386
  2. set WPDKContentRoot=c:\Program Files (x86)\Windows Kits\10
  3. InstallOEMCerts.cmd

Примените исправление, чтобы включить развертывание F5 из VS. Apply fix to enable F5 deployment from VS. В командной строке с повышенными привилегиями выполните следующие команды: In the elevated command prompt, execute the following commands:

  1. cd %TEMP% (изменит каталог на c:\users\ \Appdata\Local\Temp ) cd %TEMP% ( will change directory to c:\users\ \Appdata\Local\Temp )
  2. md “WdkTempFiles” Создание каталога «Вдктемпфилес» вручную. это обходной путь для ошибки в средствах и должен выполняться на компьютере только один раз . md “WdkTempFiles” Manually create a “WdkTempFiles” directory This is a workaround for a bug in the tooling and requires to be done only once in the PC.

Шаг 2. Инициализация устройства с помощью Visual Studio Step 2: Provision device with Visual Studio

Откройте Visual Studio и выберите драйвер > тест > настроить устройства > добавить новое устройство Open Visual Studio and select Driver > Test > Configure Devices > Add New Device

  • Если пункт меню драйвер не отображается, проверьте, установлен ли пакет SDK. If the Driver Menu option is not shown, check if SDK is installed.

В диалоговом окне Конфигурация устройства In the Device Configuration dialog,

  • Введите удобное для пользователя отображаемое имя для целевого устройства Enter a user-friendly Display Name for your target device
  • Выберите тип устройства = мобильный. Select Device Type = Mobile
  • В отображаемом списке отсортируйте по IP-адресу и найдите адрес для устройства IoT и выберите. In the list displayed, sort by IP address, and find the address for the IoT device and select. Если есть две записи, выберите одну из них с ненулевым идентификатором GUID. If there are two entries, select the one with the non-zero GUID. Убедитесь, что строка выбрана — она должна выделять синим цветом. Make sure the row is selected – it should highlight blue
  • В нижней части диалогового окна находятся два переключателя. At the bottom of the dialog are two radio buttons. Выберите тот, который говорит Device подготавливать устройство, и выберите параметры отладчика. Select the one that says Provision device and choose debugger settings. Щелкните Далее. Select Next
Читайте также:  Windows internet explorer тормозит

На странице Настройка параметров отладчиказадайте соответствующие параметры. On the Configure debugger settings, set the appropriate settings. Следует отметить следующее. Note the following:

  • Минновбоардмакс может использовать сеть для отладки. The MinnowBoardMax can use the network for debugging.
    • Использовать сеть типа подключения Use connection type Network
    • Выберите порт — по умолчанию можно использовать Select some port – default can be used
    • Выберите ключ — по умолчанию можно использовать Select some key – default can be used
    • Выберите IP-адрес узла компьютера, на котором работает Visual Studio. Select the host IP of the machine running visual studio. Не используйте адрес аутонет (169.xxx). Do not use the autonet (169.xxx) address.
    • Щелкните Далее. Select Next

  • Raspberry Pi использует последовательное подключение для отладки ядра. The Raspberry Pi uses serial for kernel debugging.
    • Подключите соответствующий кабель последовательной отладки к устройству PI и ведущему компьютеру. Connect the appropriate serial debugging cable to the PI and the host machine
    • Выберите серийный номер для типа подключения. Select Serial for the connection type
    • Заполните остальные параметры, соответствующие Raspberry Pi. Fill out the rest of the parameters as appropriate for the Raspberry Pi.
    • Щелкните Далее. Select Next

WDK в Visual Studio теперь будет подготавливать устройство IoT. The WDK, through VS, will now provision the IoT device. ТАЕФ и ВДТФ будут установлены на устройстве, и устройство будет настроено для отладки ядра в соответствии с указанными выше параметрами. TAEF and WDTF will be installed on the device, and the device will be set up for kernel debugging per the settings provided above.

По завершении устройство может быть перезагружено. When complete, the device may reboot. На экране «ход выполнения» в конфигурации устройства будет отображаться состояние и указано полное, когда устройство Интернета вещей завершило установку. The progress screen on the Device Configuration will provide status, and shows complete when the IoT device has completed the installation. Нажмите кнопку Готово. Press Finish.

  • Теперь устройство подготовлено, и в нем отображается состояние конфигурации тестирования устройства , настроенное для тестирования драйверов . The device is now provisioned and the Device test configuration status shows Configured for driver testing

Шаг 3. Настройка проекта драйвера Visual Studio Step 3: Configure Visual Studio driver project

  1. Запустите Visual Studio в режиме администратора и откройте проект драйвера Visual Studio. Launch Visual Studio in the administrator mode and open the visual studio driver project.
  2. Убедитесь, что версия целевой платформы соответствует пакету SDK, установленному на компьютере разработки. Make sure the Target Platform Version matches the SDK installed on your development machine. В окне обозреватель решений выберите Свойства проекта. Select Project Properties from the Solution Explorer window. В разделе Общие свойства конфигурации убедитесь, что версия целевой платформы соответствует пакету SDK, установленному на компьютере разработчика. Under General Configuration Properties assure that the Target Platform Version matches the SDK installed on your development computer. Версию пакета SDK можно проверить с помощью панели управления > программы > программы и компоненты. You can check the version of the SDK from the Control Panel > Programs > Programs and Features.
  3. В разделе проект > добавить новый элемент > Visual C++ > драйвер Windowsвыберите манифест пакета и нажмите кнопку добавить. Under Project > Add New Item > Visual C++ > Windows Driver, select Package Manifest and Press Add.

Package.pkg.xml файл будет добавлен в проект. Package.pkg.xml file will be added to the project. В этом файле укажите Теги «владелец», «платформа», «компонент» и «подкомпоненты». In this file, specify the Owner, Platform, Component and SubComponent tags.

  1. Задайте номер версии пакета в свойствах проекта > паккажежен > версии. Set package version number at Project Properties > PackageGen > Version. Обратите внимание, что каждый раз, когда необходимо выполнить установку или переустановку драйвера, этот номер версии должен быть увеличен. Note that every time you need to perform a Install/Reinstall of the driver, this version number has to be incremented.

  1. В разделе Свойства проекта > подписывание драйвера > тестовый сертификат, выберите тестовый сертификат (сертификат изготовителя телефона для проверки). Under Project Properties > Driver Signing > Test Certificate, select test certificate (Phone OEM Test Certificate)

  1. Перейдите к разделу Установка драйвера и выберите развертывание . Go to Driver Install and select Deployment

  • В раскрывающемся списке Target Device Name (имя целевого устройства ) выберите целевой объект, созданный выше в процессе подготовки. From the Target Device Name dropdown, select the target created above in the provisioning process. Обратите внимание на два варианта установки, переустановки и быстрой переустановки. Notice the two options for Install / Reinstall and Fast Reinstall. Выберите параметр и нажмите кнопку ОК. Choose an option and Click Ok.
  • Для первоначальной установки драйвера на целевой сервер используется Установка и повторная установка. Install / Reinstall is used for the initial installation of a driver to the target. Он устанавливает пакет драйверов с помощью стека обновлений Windows и может занять несколько минут. This installs the driver package using the Windows update stack and can take several minutes. Этот параметр должен использоваться при каждом изменении INF-файла. This must be used every time the INF file is changed.

Каждый раз, когда этот параметр используется для установки драйвера после первоначальной установки, номер версии пакета должен быть увеличен. Every time this option is used to install a driver after the initial installation, the package version number must be incremented.

  • Быстрая переустановка может быть использована после установки драйвера, и в INF-файле Drivers отсутствуют последующие изменения, влияющие на реестр. Fast Reinstall can be used once a driver has been installed, and there are no subsequent changes to the drivers INF file, which affect the registry. Этот метод обходит процесс установки, завершает работу всех девнодес, связанных с драйвером, копирует драйвер и перезапускает девноде. This method bypasses the install process, shuts down all devnodes associated with the driver, copies the driver over, and restarts the devnode. Это займет несколько ( This takes a few (
Читайте также:  Xiaomi redmi note 6 pro драйвер windows 10

Этот метод не гарантируется успешно — если по какой-либо причине девноде не может быть выключен для освобождения драйвера, операция завершится ошибкой. This method is not guaranteed to succeed – If for some reason a devnode cannot be shutdown to release the driver, the operation will fail. Это может быть вызвано сбоем оборудования или первоначальной неудачной реализацией драйвера. This can be due to faulty hardware, or an initial faulty implementation of the driver. В этом случае необходимо использовать параметр install/REINSTALL. The Install/Reinstall option must be used in this case.

Теперь проект Visual Studio готов к созданию и развертыванию драйвера на целевом устройстве. Your Visual Studio project is now ready to build and deploy a driver to your target device. Если вы используете пример драйвера гпиокмдфдемо, вам потребуется создать таблицу ACPI и скопировать ее на целевое устройство, а затем выполнить действия, описанные в разделе Создание драйвера в Visual Studio. If you are using the sample gpiokmdfdemo driver you need to generate ACPI table and copy to your target device, then follow the steps in building the driver in Visual Studio.

Шаг 4. сборка и развертывание драйвера Step 4: Build and deploy driver

Это можно сделать двумя способами: с помощью клавиши F5 и с помощью параметра deploy . This can be done in two ways, using the F5 key and using the Deploy option. В обоих случаях драйвер будет создан и развернут (т. е. установит его на устройстве), а F5 присоединит отладчик ядра Visual Studio к установленному и загруженному драйверу. In both ways, the driver will be built and deployed (i.e. installs it on device) and the F5 attaches the Visual Studio kernel debugger to the installed and loaded driver.

Некоторые пользователи предпочитают использовать функцию развертывания и присоединяют другой отладчик ядра, например WINDBG или KD. Some users prefer to use the Deploy functionality and attach a different kernel debugger, such as WinDBG or KD. Это обеспечивает большую гибкость, чем использование отладчика VS. This can provide more flexibility than using the VS debugger.

Развертывание Deploy

  1. Щелкните правой кнопкой мыши проект в обозревателе решений. Right-click on the project in the solution explorer
  2. Выбор развертывания Select Deploy

  1. Процесс развертывания должен быть продолжен. The deployment process should proceed. После развертывания устройство IoT будет перезагружено, и во время установки должен отобразиться экран «шестеренки». The IoT device will be rebooted after deployment, and should show the “Gears” screen while installation is taking place.

Выходные данные сборки находятся в окне вывода состояние развертывания. Кроме того, в окне вывода после завершения установки устройство снова перезагрузится, а на экране выходных данных VS появится сообщение об успешном или неудачном выполнении. Build output is in the Output Window Deployment status is also in the output window When Installation completes, the device will reboot again, and the VS Output screen will indicate success or failure.

F5 F5

  1. В окне сборка убедитесь, что настройки верны: Текущая сборка сборки совпадает с настройкой на целевом устройстве. From the build window, make sure that the configurations are correct – the current build arch is the same as the target device arch. Именно для этого нужно, чтобы в целевом имени была ценная дуга. This is where having the arch in the target name is valuable. Целевой объект будет отображаться в поле вид в строке меню в VS сверху вниз. The target will be displayed in the view box on the menu bar in VS on the top-middle-right.
  2. Нажмите клавишу F5. Press F5. Целевой объект будет создан, развернут и подключен к отладчику ядра VS. The target will be built, deployed, and attached to the VS Kernel Debugger.
  • После перезагрузки убедитесь, что PowerShell все еще подключен к нему, в противном случае повторно подключитесь к целевому устройству с помощью enter-pssession команды PowerShell. After the reboot, make sure PowerShell is still connected to it, otherwise, reconnect to the target device using the PowerShell enter-pssession command..

Известные проблемы Known Issues

Ошибки подготовки Provisioning Errors

Состояние гонки во время взаимодействия с Минновбоардмакс может привести к сообщению об ошибке во время подготовки. A race condition during the interaction with MinnowBoardMax can result in a reported failure during provisioning. На самом деле, подготовка, скорее всего, была успешной. In fact, the provisioning most likely succeeded.

Список ошибок: List of Errors:

  • Ошибка: не удалось успешно завершить задачу «регистрация ВДТФ». ERROR: Task «Registering WDTF» failed to complete successfully.
  • Ошибка: не удалось успешно завершить задачу «Настройка параметров отладчика ядра (возможно, перезагрузка)» ERROR: Task «Configuring kernel debugger settings (possible reboot)» failed to complete successfully

Обходной путь: Эти ошибки почти наверняка можно игнорировать. Workaround: These errors can almost certainly be ignored.

Дополнительно Details:

Следующая ошибка отобразится в диалоговом окне » ход настройки конфигурации устройства «: The following error will be displayed in the Device Configuration Configuration Progress dialog:

На этом этапе можно безопасно щелкнуть Готово , а затем Применить и ОК. At this point, you can safely click on the Finish and then the Apply and OK.

Это неопасная ошибка, сформированная состоянием гонки, приводящая к неправильной обработке журнала результатов. This is a benign error formed by a race condition causing a result log to be malformed. Это можно проверить, просмотрев файл журнала в следующей области: This can be verified by looking at the log file in the following area:

Откройте FTP-подключение к этому каталогу (как показано на экране устройства) Data/test/bin/DriverTest/Run . Open an FTP connection to the IP of the device (as shown on the device screen) to the Data/test/bin/DriverTest/Run directory. Например, ftp:// /Data/test/bin/DriverTest/Run/ e.g. ftp:// /Data/test/bin/DriverTest/Run/

Скопируйте Configuring_computer_settings_(possible_reboot)_identifier.wtl файл на локальный компьютер. copy the Configuring_computer_settings_(possible_reboot)_identifier.wtl file to your local machine. Обратите внимание, что имя файла журнала совпадает с именем невыполненной задачи. Note that the log file name matches the name of the failing task.

Откройте файл в блокноте. Open the file in notepad

Прокрутите журнал до конца. Scroll to the bottom of the log. Будет представлен следующий текст, указывающий, что подготовка выполнена успешно. The following text will be present, indicating that the provisioning is successful.

Оцените статью