Windows sdk debugging tools

Анализ дампов после BSOD с помощью Debugging Tools for Windows

Debugging Tools for Windows – это набор утилит от Microsoft, предназначенный для разработчиков и администраторов. Установщик можно бесплатно скачать по ссылке — http://msdn.microsoft.com/en-us/windows/hardware/hh852365.aspx. Перед этим, вам нужно выбрать версию ОС, в которой вы будете использовать утилиты.

Если вы разработчик драйверов и используете DDK то Debugging Tools for Windows входит туда, и его установку можно выбрать при установке DDK.

После перехода по ссылке, будет загружен веб установщик, который предложит установить Windows SDK (Software Development Kit), в который входит и Debugging Tools.

В ходе установки, вы можете выбрать только Debugging Tools

После того, как установка завершится, вам нужно найти один из файлов установки Debugging Tools. В моей Windows XP SP3 (x86) файлы установки находятся по пути — C:Program FilesMicrosoft SDKsWindowsv7.1RedistDebugging Tools for Windows. Запускаем файл dbg_x86.msi и выполняем установку.

В моей системе набор программ для отладки Debugging Tools по-умолчанию установился в каталог «C:Program FilesDebugging Tools for Windows (x86)»

Теперь нам необходим фал дампа. О том, где его взять вы можете почитать на главной странице – здесь. Если его нет, вы можете его создать с помощью утилиты NotMyFault. Давайте так и поступим, при этом, в качестве ошибки в драйвере, мы выберем DRIVER_IRQL_NOT_LESS_OR_EQUAL. Запускаем программу, выбираем “Hihg IRQL fault (Kernel-mode)” и нажимаем “Crash”. Поскольку в Windows XP, которую я использую, по-умолчанию тип дампа – малый дамп (смотрите здесь — о типах дампов), файл дампа можно найти в каталоге %Systemroot%minidump (c:windowsminidump).

Среди утилит, которые входят в Debugging Tools есть несколько, с помощью которых можно анализировать файлы дампов:

Одной из самых простых программ является dumpchk.exe. Давайте запустим ее и перенаправим вывод в файл. Мы получим приблизительно следующий результат (см. вложенный файл ниже)

По результатам анализа можно обратить внимание на следующую важную информацию.

1. Код ошибки (стоп-код) и его параметры, в файле — BugCheck 100000D1, .

2. Строку с названием драйвера, который по мнению утилиты, привел к BSOD — Probably caused by : myfault.sys ( myfault+5ab )

3. Драйвера, которые использовались в системе на момент краха, строки вида:

804d7000 806e4000 nt Sun Apr 13 21:31:06 2008 (4802516A)
806e4000 80704d00 hal Sun Apr 13 21:31:27 2008 (4802517F)
b0b90000 b0ba8b00 bthpan Sun Apr 13 21:51:32 2008 (48025634)
b0ba9000 b0beba80 bthport Sun Apr 13 21:46:29 2008 (48025505)

В простейших случаях, уже этого достаточно для того, чтобы сделать выводы относительно причин BSOD – драйвер myfault.sys как раз и используется утилитой NotMyFault, то есть, мы нашли виновника.

Вы должны были также обратить внимание на наличие в отчете строк вида:

Symbol search path is: *** Invalid ***

Your debugger is not using the correct symbols

Symbols can not be loaded because symbol path is not initialized.

Символы играют важную роль при отладке драйверов разработчиками, в том числе при анализе BSOD. Они позволяют видеть названия функций, которые используются ядром, позволяют разработчикам драйверов видеть непосредственно код на С/С++ своих драйверов, выполнение которого привело к BSOD, а также получать другую информацию. “Символы” – это общее понятие, которое относится к дополнительной информации, которая обычно записывается в файлы .pdb или в исполняемый файл, в процессе работы линковщика. Для нас важно знать, что они содержат дополнительную информацию, которая упрощает анализ дампов. Более подробную информацию о символах вы можете узнать в файле помощи к Debugging Tools — debugger.chm.

Читайте также:  Аналог xmeye для windows

Давайте запустим dumpchk.exe с параметром — “y”, который позволяет указать путь к файлам символов.

dumpchk.exe -y srv*C:Symbols*http://msdl.microsoft.com/download/symbols C:WINDOWSMinidumpMini021814-01.dmp > rep.txt

Если в каталоге c:symbols будут отсутствовать необходимые символы, они будут загружены с сайта Microsoft. Это может занять некоторое время.

Вложенный файл ниже – это результат работы dumpchk.exe с включенной опцией местонахождения символов.

Больших различий в результатах мы не видим. Они появятся когда мы выполним детальный анализ в Windbg.exe с помощью команды

analyze –v

windbg.exe -y cache*C:Symbols;srv*http://msdl.microsoft.com/download/symbols

Выбираем “File / Open Crash Dump” открываем наш файла малого дампа.

Мы также увидим сообщение о ошибке — “ERROR: Module load completed but symbols could not be loaded for myfault.sys”. Так и должно быть поскольку для этого драйвера файлы символы не представлены. Теперь в строке ввода команд давайте введем:

!analyze -v

Мы получи намного больше информации, чем в случае использования dumpchk.exe (см. вложенный файл)

DRIVER_IRQL_NOT_LESS_OR_EQUAL (d1)
An attempt was made to access a pageable (or completely invalid) address at an
interrupt request level (IRQL) that is too high. This is usually
caused by drivers using improper addresses.
If kernel debugger is available get stack backtrace.
Arguments:
Arg1: e2ee9008, memory referenced
Arg2: 00000002, IRQL
Arg3: 00000000, value 0 = read operation, 1 = write operation
Arg4: badbc5ab, address which referenced memory

FAULTING_IP:
myfault+5ab
badbc5ab 8b08 mov ecx,dword ptr [eax]

LAST_CONTROL_TRANSFER: from badbc9db to badbc5ab

STACK_TEXT:
WARNING: Stack unwind information not available. Following frames may be wrong.
b08f6bfc badbc9db 898ae698 b08f6c40 badbcb26 myfault+0x5ab
b08f6c08 badbcb26 8936b740 00000001 00000000 myfault+0x9db
b08f6c40 804ef18f 89668958 898ae698 806e6410 myfault+0xb26
b08f6c50 8057f982 898ae708 8936b740 898ae698 nt!IopfCallDriver+0x31
b08f6c64 805807f7 89668958 898ae698 8936b740 nt!IopSynchronousServiceTail+0x70
b08f6d00 80579274 00000094 00000000 00000000 nt!IopXxxControlFile+0x5c5
b08f6d34 8054161c 00000094 00000000 00000000 nt!NtDeviceIoControlFile+0x2a
b08f6d34 7c90e4f4 00000094 00000000 00000000 nt!KiFastCallEntry+0xfc
0006f8e0 00000000 00000000 00000000 00000000 0x7c90e4f4

FOLLOWUP_IP:
myfault+5ab
badbc5ab 8b08 mov ecx,dword ptr [eax]

Давайте рассмотрим полученную информацию.

1. DRIVER_IRQL_NOT_LESS_OR_EQUAL (d1) – это символическое описание ошибки

2. У данной ошибки, есть 4-е параметра, которые позволяют получить дополнительную информацию, все они представлены ниже

Arg1: e2ee9008, memory referenced (адрес памяти по которому происходило обращение)
Arg2: 00000002, IRQL (уровень IRQL на момент обращения)
Arg3: 00000000, value 0 = read operation, 1 = write operation (тип операции, в нашем случае, это операция чтения)
Arg4: badbc5ab, address which referenced memory (адрес в памяти инструкции, которая выполняла операцию чтения)

FAULTING_IP:
myfault+5ab
badbc5ab 8b08 mov ecx,dword ptr [eax]

Здесь показана непосредственно инструкция которая выполнялась – операция записи в регистр ecx содержимого по адресу указанному в eax. Эта инструкция находится по адресу myfault+5ab и относится к драйверу myfault.sys (myfault – это имя драйвера).

Это имя процесса пользовательского режима, который выполнялся во время краха.

STACK_TEXT:
WARNING: Stack unwind information not available. Following frames may be wrong.
b08f6bfc badbc9db 898ae698 b08f6c40 badbcb26 myfault+0x5ab
b08f6c08 badbcb26 8936b740 00000001 00000000 myfault+0x9db
b08f6c40 804ef18f 89668958 898ae698 806e6410 myfault+0xb26
b08f6c50 8057f982 898ae708 8936b740 898ae698 nt!IopfCallDriver+0x31
b08f6c64 805807f7 89668958 898ae698 8936b740 nt!IopSynchronousServiceTail+0x70
b08f6d00 80579274 00000094 00000000 00000000 nt!IopXxxControlFile+0x5c5
b08f6d34 8054161c 00000094 00000000 00000000 nt!NtDeviceIoControlFile+0x2a
b08f6d34 7c90e4f4 00000094 00000000 00000000 nt!KiFastCallEntry+0xfc
0006f8e0 00000000 00000000 00000000 00000000 0x7c90e4f4

Это стек вызовов режима ядра. В отличии от стека процесса пользовательского режима, стек ядра один. Благодаря стеку мы видим, что последовательность вызовов была следующей:

С Ntdll.dll была вызвана функция KiFastCallEntry, которая затем вызвала NtDeviceIoControlFile и т.д., пока при выполнении инструкции по адресу myfault+0x5ab не произошел крах системы.

Читайте также:  Драйвера для тачпада dell windows 10

Анализ данных говорит нам о том, что виновником BSOD был драйвер myfault (myfault.sys)

Если бы мы не использовали символы, у нас была бы следующая информация о стеке

b08f6bfc badbc9db 898ae698 b08f6c40 badbcb26 myfault+0x5ab
b08f6c08 badbcb26 8936b740 00000001 00000000 myfault+0x9db
b08f6c40 804ef18f 89668958 898ae698 806e6410 myfault+0xb26
b08f6c64 805807f7 89668958 898ae698 8936b740 nt+0x1818f
b08f6d00 80579274 00000094 00000000 00000000 nt+0xa97f7
b08f6d34 8054161c 00000094 00000000 00000000 nt+0xa2274
b08f6d64 7c90e4f4 badb0d00 0006f888 b11b2d98 nt+0x6a61c
b08f6d68 badb0d00 0006f888 b11b2d98 b11b2dcc 0x7c90e4f4
b08f6d6c 0006f888 b11b2d98 b11b2dcc 00000000 vmscsi+0xd00
b08f6d70 b11b2d98 b11b2dcc 00000000 00000000 0x6f888
b08f6d74 b11b2dcc 00000000 00000000 00000000 0xb11b2d98
b08f6d78 00000000 00000000 00000000 00000000 0xb11b2dcc

Что менее информативно.

Вообще анализ дампов, кроме самых простых случаев (таких как рассмотренный) требует значительной подготовки и хорошего понимания как работы ОС и драйверов так и владение знанием ассемблера. В открытом доступе можно найти некоторые книги Дмитрия Востокова «Memory Dump Analysis Antology». Если вы их найдете, вы сможете приблизительно оценить уровень автора и приблизительно понять нетривиальность анализа дампов.

Getting Started with Windows Debugging

This article covers how to get started with Windows Debugging. If your goal is to use the debugger to analyze a crash dump, see Analyze crash dump files by using WinDbg.

To get started with Windows Debugging, complete the tasks that are described in this article.

1. Determine the host and the target

The debugger runs on the host system, and the code that you want to debug runs on the target system.

Host Target

Because it is common to stop instruction execution on the processor during debugging, two computer systems are typically used. In some situations, you might be able to use a virtual machine as the second system. For example, you might be able to use a virtual PC that is running on the same PC as the code that you need to debug. However, if your code is communicating to low-level hardware, using a virtual PC may not be the best approach. For more information, see Setting up network debugging of a virtual machine — KDNET.

2. Determine the type: kernel-mode or user-mode

Next, you need to determine whether you will do kernel-mode or user-mode debugging.

Kernel mode is the processor-access mode in which the operating system and privileged programs run. Kernel-mode code has permission to access any part of the system, and it is not restricted like user-mode code. Kernel-mode code can gain access to any part of any other process running in either user mode or kernel mode. Much of the core OS functionality and many hardware device drivers run in kernel mode.

User mode is the mode that applications and subsystems on the computer run in. Processes that run in user mode do so within their own virtual address spaces. They are restricted from gaining direct access to many parts of the system, including system hardware, memory that was not allocated for their use, and other portions of the system that might compromise system integrity. Because processes that run in user mode are effectively isolated from the system and other user-mode processes, they cannot interfere with these resources.

If your goal is to debug a driver, determine if the driver is a kernel-mode driver or a user-mode driver. Windows Driver Model (WDM) drivers and Kernel-Mode Driver Framework (KMDF) are both kernel-mode drivers. As the name sugests, User-Mode Driver Framework (UMDF) drivers are user-mode drivers.

For some issues, it can be difficult to determine which mode the code executes in. In that case, you may need to pick one mode and look to see what information is available in that mode. Some issues require using the debugger in both user mode and kernel mode.

Читайте также:  Как разблокировать windows lock

Depending on what mode you decide to debug in, you will need to configure and use the debuggers in different ways. Some debugging commands operate the same in both modes, and some commands operate differently in different modes.

For information about using the debugger in kernel mode, see the following articles:

For information about using the debugger in user mode, see Getting started with WinDbg (user-mode).

3. Choose your debugger environment

WinDbg works well in most situations, but there are times when you may want to use another debugger, such as console debuggers for automation or Visual Studio. For more information, see Debugging environments.

4. Determine how to connect the target and host

Typically, target and host systems are connected by an Ethernet network. If you are doing early bring-up work, or you don’t have an Ethernet connection on a device, other network connection options are available. For more information, see these articles:

5. Choose either the 32-bit or 64-bit debugging tools

Which debugging tools to choose—32-bit or 64-bit—depends on the version of Windows that is running on the target and host systems and on whether you are debugging 32-bit or 64-bit code. For more information, see Choosing the 32-Bit or 64-Bit debugging tools.

6. Configure symbols

To use all of the advanced functionality that WinDbg provides, you must load the proper symbols. If you do not have symbols properly configured, you will receive messages indicating that symbols are not available when you attempt to use functionality that is dependent on symbols. For more information, see Symbols for Windows debugging (WinDbg, KD, CDB, NTSD).

7. Configure source code

If your goal is to debug your own source code, you will need to configure a path to your source code. For more information, see Source path.

8. Become familiar with debugger operation

The Debugger operation section of this documentation describes debugger operation for various tasks. For example, Loading debugger extension DLLs explains how to load debugger extensions. To learn more about working with WinDbg, see Debugging using WinDbg.

9. Become familiar with debugging techniques

Standard debugging techniques apply to most debugging scenarios, and examples include setting breakpoints, inspecting the call stack, and finding a memory leak. Specialized debugging techniques apply to particular technologies or types of code. Examples include Plug and Play debugging, KMDF debugging, and RPC debugging.

10. Use the debugger reference commands

Over time, you will use different debugging commands as you work in the debugger. Use the .hh (open HTML help file) command in the debugger to display help information about any debugging command. For more information about the available commands, see Debugger reference.

11. Use debugging extensions for specific technologies

There are multiple debugging extensions that provide parsing of domain-specific data structures. For more information, see Specialized extensions.

This documentation assumes a knowledge of Windows internals. To learn more about Windows internals (including memory usage, context, threads, and processes), review additional resources, such as Windows Internals by Mark Russinovich, David Solomon, and Alex Ionescu.

13. Review additional debugging resources

Additional resources include the following books and videos:

  • Inside Windows Debugging: Practical Debugging and Tracing Strategies by Tarik Soulami
  • Advanced Windows Debugging by Mario Hewardt and Daniel Pravat
  • Defrag Tools, episodes 13 through 29, about WinDbg
Оцените статью