Как включить отладчик windows

Отладчик Windows (WinDbg) Windows Debugger (WinDbg)

Отладка устройства Windows 10 IoT базовая с помощью мощного отладчика Windows, WinDbg. Debug your Windows 10 IoT Core device using the powerful Windows debugger, WinDbg.

В следующих разделах описывается, как успешно подключиться с WinDbg к устройству Windows 10 IoT базовая для отладки. The following sections describe how to successfully connect with WinDbg to a Windows 10 IoT Core device for debugging purposes. Сюда входит описание необходимых параметров программного обеспечения на устройстве, а также физические подключения оборудования. This includes a description of the necessary software settings on the device as well as the physical hardware connections.

WinDbg — очень мощный отладчик, с которым знакомы большинство разработчиков Windows. WinDbg is a very powerful debugger that most Windows developers are familiar with. Однако если вы только приступите к работе и хотите узнать больше о WinDbg, перейдите по следующим ссылкам: However, if you are just getting started and would like to learn more about WinDbg, please visit the following links:

MinnowBoard Max (МИКРОТЕСТОВ) MinnowBoard Max (MBM)

Вы можете подключить WinDbg к устройству MinnowBoard Max с помощью сетевого подключения. You can connect WinDbg to the MinnowBoard Max device using a network connection.

Настройка сетевого подключения Setup network connection

Чтобы включить отладку ядра с помощью WinDbg по сети, убедитесь, что: In order to enable kernel debugging with WinDbg over a network, ensure that:

Кабель Ethernet подключен к сети MinnowBoard Max Device. An Ethernet cable is connected to MinnowBoard Max device to your network

MinnowBoard Max Device имеет допустимый IP-адрес в вашей сети. The MinnowBoard Max device has a valid IP address in your network

Активное подключение к устройству MinnowBoard Max с помощью PowerShell An active connection to the MinnowBoard Max device via PowerShell

Используя активное подключение PowerShell, выполните следующие команды в параметре MinnowBoard Max, чтобы включить отладку по сети. Using the active PowerShell connection, execute the following commands on the MinnowBoard Max to enable debugging over the network.

bcdedit -dbgsettings net hostip: port:

Эта команда включает отладку по сети. This command enables debugging over the network. Кроме того, он указывает IP-адрес компьютера, на котором будет выполняться WinDbg (DEV_PC_IP_ADDRESS), номер сетевого порта, используемого для подключения (PORT_NUM), и уникальный ключ, который будет использоваться для различения нескольких подключений (ключ). Additionally, it specifies the IP address of the PC where WinDbg will be running (DEV_PC_IP_ADDRESS), the network port number to use for the connection (PORT_NUM), and a unique key to be used to differentiate multiple connections (KEY)

Для PORT_NUM и ключа можно использовать следующие значения в качестве примеров: 50045 и 1.2.3.4 соответственно, хотя вы можете изменить их по своему усмотрению. For PORT_NUM and KEY, you can use the following values as examples: 50045 and 1.2.3.4 respectively, although you are free to change them as you see fit

bcdedit -debug on

  • Эта команда включает отладку на устройстве This command turns on debugging on the device

На компьютере разработчика запустите WinDbg с PORT_NUM и КЛЮЧЕВЫМи значениями, приведенными в предыдущих шагах, как показано ниже. «c:\Program Files (x86)\Debugging Tools for Windows (x86)\windbg.exe» -k net:port=

,key= On the developer PC, start WinDbg with the PORT_NUM and the KEY values provided in the previous steps as follows: «c:\Program Files (x86)\Debugging Tools for Windows (x86)\windbg.exe» -k net:port=

Если вы установили любой из установленных комплектов Windows, вы можете найти WinDbg в разделе C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\WinDbg.exe If you have any of the Windows kits installed, you may find WinDbg under C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\WinDbg.exe

  • Перезагрузка устройства Иоткоре для повторного подключения к отладчику Reboot the IoTCore device to reconnect to the debugger

Raspberry Pi 2 или 3 (RPi2 или RPi3) Raspberry Pi 2 or 3 (RPi2 or RPi3)

Вы можете подключить WinDbg к Raspberry Pi 2 или 3 с помощью последовательного подключения. You can connect WinDbg to the Raspberry Pi 2 or 3 using a serial connection.

Настройка последовательного подключения Setup serial connection

Чтобы включить отладку ядра с помощью WinDbg через последовательное подключение, убедитесь, что: In order to enable kernel debugging with WinDbg over a serial connection, ensure that:

У вас есть отладочный кабель, такой как последовательный кабель от USB до TTL от Adafruit или фтди. You have a debug cable such as the USB-to-TTL Serial Cable from Adafruit or FTDI.

Кабель Ethernet или активный WiFi, соединяющий устройство Raspberry Pi 2 или 3 с вашей сетью (для IP-подключений, таких как SSH или PowerShell). An Ethernet cable or active WiFi connecting your Raspberry Pi 2 or 3 device to your network (for IP connections like SSH or PowerShell)

Читайте также:  Windows downloads updates but fails install

Устройство Raspberry Pi 2 или 3 имеет допустимый IP-адрес в сети The Raspberry Pi 2 or 3 device has a valid IP address in your network

Активное подключение к устройству Raspberry Pi 2 или 3 с помощью PowerShell или SSH An active connection to the Raspberry Pi 2 or 3 device via PowerShell or SSH

UART0 будет использоваться на устройстве Raspberry Pi 2 или 3 для подключения отладки ядра. UART0 will be used on the Raspberry Pi 2 or 3 device for the kernel debugging connection. Ниже показаны сопоставления ПИН-кода для Raspberry Pi 2 или 3, а также последовательных кабелей: The following shows the pin mappings for the Raspberry Pi 2 or 3 as well as the serial cables:

Основная идея для создания правильных последовательных подключений заключается в том, что хотя одно устройство использует его для передачи данных, другое устройство использует RX для получения данных. The basic idea for making the correct serial connections is to remember that while one device uses its TX to transmit data, the other device uses its RX to receive the data. Ниже перечислены рекомендуемые подключения. Recommended connections are listed below:

Соединение ЕФИЕСП больше не создается. The EFIESP junction is no longer created. Его необходимо подключить самостоятельно. для получения идентификатора GUID можно использовать команду mountvol. You’ll have to mount it yourself,you can use mountvol command to get the GUID. mkdir C:\EFIESP mountvol C:\EFIESP \?\Volume

Используя активное подключение PowerShell, выполните следующие команды на устройстве Raspberry Pi 2 или 3, чтобы включить отладку по последовательному подключению. Using the active PowerShell connection, execute the following commands on the Raspberry Pi 2 or 3 device to enable debugging over the serial connection.

bcdedit /store c:\EFIESP\EFI\Microsoft\Boot\BCD -dbgsettings serial

  • Приведенная выше команда включает последовательное подключение для отладки. The above command enables the serial connection for debugging
  • Скорость передачи для Raspberry Pi 2 или 3 жестко запрограммирована на 921600, поэтому вам не нужно указывать его. The baud-rate for the Raspberry Pi 2 or 3 is hard-coded to 921600, so you don’t have to specify it

bcdedit /store c:\EFIESP\EFI\Microsoft\Boot\BCD -debug on

  • Эта команда включает отладку на устройстве This command turns on debugging on the device

На компьютере разработчика получите порт номера порта COM, назначенный в системе для кабеля USB – TTL. On the developer PC, get the COM port number PORT assigned in the system for the USB-to-TTL cable. Он будет доступен в Device Manager в разделе «порты (COM & LPT)». This will be available in Device Manager under «Ports (COM & LPT)».

«C:\Program Files (x86)\Debugging Tools for Windows (x86)\windbg.exe» -k com:port=

  • Запуск WinDbg с номером порта Start WinDbg with the PORT number

Если вы установили любой из установленных комплектов Windows, вы можете найти WinDbg в разделе C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\WinDbg.exe If you have any of the Windows kits installed, you may find WinDbg under C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\WinDbg.exe

  • Перезагрузка устройства Иоткоре для повторного подключения к отладчику Reboot the IoTCore device to reconnect to the debugger

Драгонбоард (DB) DragonBoard (DB)

Вы можете подключить WinDbg к Драгонбоард с помощью последовательного или USB-подключения. You can connect WinDbg to the DragonBoard using a serial or USB connection.

Используя активное подключение PowerShell или SSH к Драгонбоард, выполните следующие команды, чтобы включить отладку. Using the active PowerShell or SSH connection to your DragonBoard, execute the following commands to enable debugging.

  • bcdedit /store c:\EFIESP\EFI\Microsoft\Boot\BCD /debug ON
    • Включает отладчик Enables the debugger

Настройка USB-подключения Setup USB connection

По умолчанию параметры отладчика USB настраиваются в тестовых образах. By default the USB debugger settings are configured in the test images.

Когда отладчик ядра USB включен, порты USB на устройстве Драгонбоард могут не работать (например, клавиатура, USB-порт Ethernet может не работать). Once USB kernel debugger is on, USB ports on the DragonBoard device might not work (i.e. keyboard, usb ethernet might not work).

Настройка последовательного подключения Setup serial connection

bcdedit /store c:\EFIESP\EFI\Microsoft\Boot\BCD /dbgsettings Serial debugport:1 baudrate:115200

  • Настраивает последовательный порт Configures the serial port

Перезагрузка устройства Иоткоре для повторного подключения к отладчику Reboot the IoTCore device to reconnect to the debugger

Практическое руководство. Отладка приложений служб Windows How to: Debug Windows Service Applications

Служба должна запускаться из диспетчера управления службами, а не из Visual Studio. A service must be run from within the context of the Services Control Manager rather than from within Visual Studio. Поэтому, процесс отладки службы сложнее, чем отладка приложений Visual Studio других типов. For this reason, debugging a service is not as straightforward as debugging other Visual Studio application types. Для отладки службы необходимо запустить службу, а затем подключить отладчик к процессу, в котором она выполняется. To debug a service, you must start the service and then attach a debugger to the process in which it is running. Приложение можно отлаживать с помощью всех стандартных средств отладки Visual Studio. You can then debug your application by using all of the standard debugging functionality of Visual Studio.

Не следует присоединять к процессу, если неизвестно, что собой представляет данный процесс, и неясны последствия подключения к процессу (включая даже уничтожение этого процесса). You should not attach to a process unless you know what the process is and understand the consequences of attaching to and possibly killing that process. Например, при подключении к процессу WinLogon и последующей остановке процесса отладки система будет остановлена, так как она не может работать без данного процесса. For example, if you attach to the WinLogon process and then stop debugging, the system will halt because it can’t operate without WinLogon.

Отладчик можно прикреплять только к выполняющейся службе. You can attach the debugger only to a running service. Процесс подключения прерывает текущую работу службы (фактически он не останавливает и не приостанавливает ее). The attachment process interrupts the current functioning of your service; it doesn’t actually stop or pause the service’s processing. То есть, если служба уже выполнялась на момент запуска процесса отладки, она по-прежнему технически находится в состоянии «Started» в ходе отладки, однако ее работа приостанавливается. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.

После присоединения к процессу можно установить точки останова и использовать их для отладки кода. After attaching to the process, you can set breakpoints and use these to debug your code. После выхода из диалогового окна, используемого для подключения к процессу, вы продолжаете оставаться в режиме отладки. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. Для запуска, остановки, приостановки и продолжения работы служб (то есть, попадания в заданные точки) можно использовать диспетчер управления службами. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you’ve set. Позднее эту фиктивную службу можно удалить после успешного завершения отладки. You can later remove this dummy service after debugging is successful.

В этой статье рассматривается процесс отладки службы, выполняемой на локальном компьютере (также можно выполнять отладку служб Windows, которые выполняются на удаленном компьютере). This article covers debugging a service that’s running on the local computer, but you can also debug Windows Services that are running on a remote computer. См. статью об удаленной отладке. See Remote Debugging.

Процесс отладки метода OnStart может быть сложным, так как диспетчер управления службами накладывает ограничение в 30 секунд на все попытки запуска службы. Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all attempts to start a service. Дополнительные сведения см. в статье Устранение неполадок. Отладка служб Windows. For more information, see Troubleshooting: Debugging Windows Services.

Для получения значимой информации для отладки отладчик Visual Studio должен найти файлы символов для двоичных файлов, для которых выполняется отладка. To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that are being debugged. При отладке службы, созданной в Visual Studio, файлы символов (PDB-файлы) находятся в той же папке, что и исполняемый файл или библиотека, и отладчик загружает их автоматически. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the same folder as the executable or library, and the debugger loads them automatically. При отладке службы, которая не была построена, сначала следует найти символы для службы и убедиться, что они могут быть найдены отладчиком. If you are debugging a service that you didn’t build, you should first find symbols for the service and make sure they can be found by the debugger. См. руководство по определению файлов символов (.pdb) и файлов с исходным кодом в отладчике Visual Studio. See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. Если вы выполняете отладку системного процесса или хотите иметь символы для системных вызовов в своих службах, то необходимо добавить серверы символов Майкрософт. If you’re debugging a system process or want to have symbols for system calls in your services, you should add the Microsoft Symbol Servers. См. статью об отладке с помощью символов. See Debugging Symbols.

Отладка службы To debug a service

Постройте службу в конфигурации отладки. Build your service in the Debug configuration.

Установите службу. Install your service. Дополнительные сведения см. в разделе Практическое руководство. Установка и удаление служб. For more information, see How to: Install and Uninstall Services.

Запустите службу из диспетчера служб, обозревателя сервера или из кода. Start your service, either from Services Control Manager, Server Explorer, or from code. Дополнительные сведения см. в разделе Практическое руководство. Запуск служб. For more information, see How to: Start Services.

Запустите Visual Studio с учетными данными администратора, чтобы вы могли подключиться к системным процессам. Start Visual Studio with administrative credentials so you can attach to system processes.

(Необязательное действие.) В строке меню Visual Studio последовательно выберите Инструменты и Параметры. (Optional) On the Visual Studio menu bar, choose Tools, Options. В диалоговом окне Параметры последовательно выберите Отладка и Символы, установите флажок Серверы символов Microsoft и нажмите кнопку ОК. In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button.

В строке меню в меню Отладка или Инструменты выберите пункт Присоединение к процессу. On the menu bar, choose Attach to Process from the Debug or Tools menu. (Клавиатура: CTRL+ALT+P) (Keyboard: Ctrl+Alt+P)

Откроется диалоговое окно Процессы. The Processes dialog box appears.

Установите флажок Показать процессы, запущенные всеми пользователями. Select the Show processes from all users check box.

В разделе Доступные процессы выберите процесс для службы и нажмите кнопку Присоединиться. In the Available Processes section, choose the process for your service, and then choose Attach.

Процесс будет иметь то же имя, что и исполняемый файл для службы. The process will have the same name as the executable file for your service.

Откроется диалоговое окно Присоединение к процессу . The Attach to Process dialog box appears.

Выберите соответствующие параметры, а затем нажмите кнопку ОК, чтобы закрыть диалоговое окно. Choose the appropriate options, and then choose OK to close the dialog box.

Теперь вы находитесь в режиме отладки. You are now in debug mode.

Установите точки останова, которые буден нужно использовать в коде. Set any breakpoints you want to use in your code.

Откройте диспетчер управления службами и выполните несколько операций со своей службой (выполните команды остановки, приостановки и продолжения), чтобы обнаружить свои точки останова. Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints. Дополнительные сведения о запуске диспетчера управления службами см. в разделе Практическое руководство. Запуск служб. For more information about running the Services Control Manager, see How to: Start Services. Также см. раздел Устранение неполадок. Отладка служб Windows. Also, see Troubleshooting: Debugging Windows Services.

Советы по отладке для служб Windows Debugging Tips for Windows Services

Присоединение к процессу службы позволяет отлаживать основную часть кода (но не весь код) для этой службы. Attaching to the service’s process allows you to debug most, but not all, the code for that service. Например, так как служба уже была запущена, нельзя выполнять отладку кода в методе OnStart службы или кода в методе Main , который используется для загрузки службы подобным образом. For example, because the service has already been started, you cannot debug the code in the service’s OnStart method or the code in the Main method that is used to load the service this way. Одним из способов обхода этого ограничения является создание временной второй службы в приложении службы, которая предназначена только для отладки. One way to work around this limitation is to create a temporary second service in your service application that exists only to aid in debugging. Можно установить обе службы,а затем запустить эту фиктивную службу для загрузки процесса службы. You can install both services, and then start this dummy service to load the service process. Когда временная служба запустит процесс, в Visual Studio в меню Отладка можно будет присоединиться к процессу службы. Once the temporary service has started the process, you can use the Debug menu in Visual Studio to attach to the service process.

Попробуйте добавлять вызовы в метод Sleep с целью задержки выполнения действия, пока вы не присоединитесь к процессу. Try adding calls to the Sleep method to delay action until you’re able to attach to the process.

Попробуйте заменить программу на обычное консольное приложение. Try changing the program to a regular console application. Для этого измените метод Main следующим образом, чтобы он мог быть запущен и как служба Windows, и как консольное приложение (в зависимости от способа запуска). To do this, rewrite the Main method as follows so it can run both as a Windows Service and as a console application, depending on how it’s started.

Практическое руководство. Запуск службы Windows как консольного приложения How to: Run a Windows Service as a console application

Добавьте метод в свою службу, которая запускает методы OnStart и OnStop: Add a method to your service that runs the OnStart and OnStop methods:

Перепишите метод Main следующим образом: Rewrite the Main method as follows:

В окне свойств проекта на вкладке Приложение задайте для параметра Тип выходных данных значение Консольное приложение. In the Application tab of the project’s properties, set the Output type to Console Application.

Щелкните Начать отладку (F5). Choose Start Debugging (F5).

Чтобы снова запустить программу как службу Windows, установите ее и запустите обычным образом (для службы Windows). To run the program as a Windows Service again, install it and start it as usual for a Windows Service. Отменять эти изменения необязательно. It’s not necessary to reverse these changes.

В некоторых случаях, например, если требуется устранить некоторую проблему, которая возникает только при запуске системы, необходимо использовать отладчик Windows. In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the Windows debugger. Скачайте набор драйверов Windows (WDK) и узнайте о способах отладки служб Windows. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.

Читайте также:  Conexant 20671 smartaudio hd driver windows 10
Оцените статью