Windows kernel dump debugger

Dump files in the Visual Studio debugger

A dump file is a snapshot that shows the process that was executing and modules that were loaded for an app at a point in time. A dump with heap information also includes a snapshot of the app’s memory at that point.

Opening a dump file with a heap in Visual Studio is something like stopping at a breakpoint in a debug session. Although you can’t continue execution, you can examine the stacks, threads, and variable values of the app at the time of the dump.

Dumps are mostly used to debug issues from machines that developers don’t have access to. You can use a dump file from a customer’s machine when you can’t reproduce a crash or unresponsive program on your own machine. Testers also create dumps to save crash or unresponsive program data to use for more testing.

The Visual Studio debugger can save dump files for managed or native code. It can debug dump files created by Visual Studio or by other apps that save files in the minidump format.

Requirements and limitations

To debug dump files from 64-bit machines, Visual Studio must be running on a 64-bit machine.

Visual Studio can debug dump files of native apps from ARM devices. It can also debug dumps of managed apps from ARM devices, but only in the native debugger.

To debug kernel-mode dump files or use the SOS.dll debugging extension in Visual Studio, download the debugging tools for Windows in the Windows Driver Kit (WDK).

Visual Studio can’t debug dump files saved in the older, full user-mode dump format. A full user-mode dump is not the same as a dump with heap.

Debugging dump files of optimized code can be confusing. For example, compiler inlining of functions can result in unexpected call stacks, and other optimizations might change the lifetime of variables.

Dump files with or without heaps

Dump files may or may not have heap information.

Dump files with heaps contain a snapshot of the app’s memory, including the values of variables, at the time of the dump. Visual Studio also saves the binaries of loaded native modules in a dump file with a heap, which can make debugging much easier. Visual Studio can load symbols from a dump file with a heap, even if it can’t find an app binary.

Dump files without heaps are much smaller than dumps with heaps, but the debugger must load the app binaries to find symbol information. The loaded binaries must exactly match the ones running during dump creation. Dump files without heaps save the values of stack variables only.

Create a dump file

While you are debugging a process in Visual Studio, you can save a dump when the debugger has stopped at an exception or breakpoint.

With Just-In-Time Debugging enabled, you can attach the Visual Studio debugger to a crashed process outside of Visual Studio, and then save a dump file from the debugger. See Attach to running processes.

To save a dump file:

While stopped at an error or breakpoint during debugging, select Debug > Save Dump As.

In the Save Dump As dialog box, under Save as type, select Minidump or Minidump with Heap (the default).

Browse to a path and select a name for the dump file, and then select Save.

You can create dump files with any program that supports the Windows minidump format. For example, the Procdump command-line utility from Windows Sysinternals can create process crash dump files based on triggers or on demand. See Requirements and limitations for information about using other tools to create dump files.

Open a dump file

In Visual Studio, select File > Open > File.

In the Open File dialog box, locate and select the dump file. It will usually have a .dmp extension. Select OK.

The Minidump File Summary window shows summary and module information for the dump file, and actions you can take.

Under Actions:

  • To set symbol loading locations, select Set symbol paths.
  • To start debugging, select Debug with Managed Only, Debug with Native Only, Debug with Mixed, or Debug with Managed Memory.
Читайте также:  Суфд настройка рабочего места windows

Find .exe, .pdb, and source files

To use full debugging features on a dump file, Visual Studio needs:

  • The .exe file the dump was created for, and other binaries (DLLs, etc.) that the dump process used.
  • Symbol (.pdb) files for the .exe and other binaries.
  • The .exe and .pdb files that exactly match the version and build of the files at dump creation.
  • Source files for the relevant modules. You can use the disassembly of the modules if you can’t find the source files.

If the dump has heap data, Visual Studio can cope with missing binaries for some modules, but it must have binaries for enough modules to generate valid call stacks.

Search paths for .exe files

Visual Studio automatically searches these locations for .exe files that aren’t included in the dump file:

  1. The folder that contains the dump file.
  2. The module path the dump file specifies, which is the module path on the machine that collected the dump.
  3. The symbol paths specified in Tools (or Debug) >Options >Debugging >Symbols. You can also open the Symbols page from the Actions pane of the Dump File Summary window. On this page, you can add more locations to search.

Use the No Binary, No Symbols, or No Source Found pages

If Visual Studio can’t find the files it needs to debug a module in the dump, it shows a No Binary Found, No Symbols Found, or No Source Found page. These pages provide detailed information about the cause of the issue, and provide action links that can help you locate the files. See Specify symbol (.pdb) and source files.

Analyzing a Kernel-Mode Dump File with WinDbg

Kernel-mode memory dump files can be analyzed by WinDbg. The processor or Windows version that the dump file was created on does not need to match the platform on which KD is being run.

Starting WinDbg

To analyze a dump file, start WinDbg with the -z command-line option:

windbg -y SymbolPath -i ImagePath -z DumpFileName

The -v option (verbose mode) is also useful. For a full list of options, see WinDbg Command-Line Options.

If WinDbg is already running and is in dormant mode, you can open a crash dump by selecting the File | Open Crash Dump menu command or pressing the CTRL+D shortcut key. When the Open Crash Dump dialog box appears, enter the full path and name of the crash dump file in the File name text box, or use the dialog box to select the proper path and file name. When the proper file has been chosen, select Open.

You can also open a dump file after the debugger is running by using the .opendump (Open Dump File) command, followed with g (Go).

It is possible to debug multiple dump files at the same time. This can be done by including multiple -z switches on the command line (each followed by a different file name), or by using .opendump to add additional dump files as debugger targets. For information about how to control a multiple-target session, see Debugging Multiple Targets.

Dump files generally end with the extension .dmp or .mdmp. You can use network shares or Universal Naming Convention (UNC) file names for the memory dump file.

It is also common for dump files to be packed into a CAB file. If you specify the file name (including the .cab extension) after the -z option or as the argument to an .opendump command, the debugger can read the dump files directly out of the CAB. However, if there are multiple dump files stored in a single CAB, the debugger will only be able to read one of them. The debugger will not read any additional files from the CAB, even if they were symbol files or other files associated with the dump file.

Analyzing the Dump File

If you are analyzing a Kernel Memory Dump or a Small Memory Dump, you may need to set the executable image path to point to any executable files that may have been loaded in memory at the time of the crash.

Analysis of a dump file is similar to analysis of a live debugging session. See the Debugger Commands reference section for details on which commands are available for debugging dump files in kernel mode.

In most cases, you should begin by using !analyze. This extension command performs automatic analysis of the dump file and can often result in a lot of useful information.

Читайте также:  Iphone android blackberry windows phone

The .bugcheck (Display Bug Check Data) shows the bug check code and its parameters. Look up this bug check in the Bug Check Code Reference for information about the specific error.

The following debugger extensions are especially useful for analyzing a kernel-mode crash dump:

For techniques that can be used to read specific kinds of information from a dump file, see Extracting Information from a Dump File.

Анализ дампа памяти в Windows при BSOD с помощью WinDBG

В момент критического сбоя операционная система Windows прерывает работу и показывает синий экран смерти (BSOD). Содержимое оперативной памяти и вся информация о возникшей ошибке записывается в файл подкачки. При следующей загрузке Windows создается аварийный дамп c отладочной информацией на основе сохраненных данных. В системном журнале событий создается запись о критической ошибке.

Типы аварийных дампов памяти Windows

На примере актуальной операционной системы Windows 10 (Windows Server 2016) рассмотрим основные типы дампов памяти, которые может создавать система:

  • Мини дамп памяти (Small memory dump) (256 КБ). Этот тип файла включает минимальный объем информации. Он содержит только сообщение об ошибке BSOD, информацию о драйверах, процессах, которые были активны в момент сбоя, а также какой процесс или поток ядра вызвал сбой.
  • Дамп памяти ядра (Kernel memory dump). Как правило, небольшой по размеру — одна треть объема физической памяти. Дамп памяти ядра является более подробным, чем мини дамп. Он содержит информацию о драйверах и программах в режиме ядра, включает память, выделенную ядру Windows и аппаратному уровню абстракции (HAL), а также память, выделенную драйверам и другим программам в режиме ядра.
  • Полный дамп памяти (Complete memory dump). Самый большой по объему и требует памяти, равной оперативной памяти вашей системы плюс 1MB, необходимый Windows для создания этого файла.
  • Автоматический дамп памяти (Automatic memory dump). Соответствует дампу памяти ядра с точки зрения информации. Отличается только тем, сколько места он использует для создания файла дампа. Этот тип файлов не существовал в Windows 7. Он был добавлен в Windows 8.
  • Активный дамп памяти (Active memory dump). Этот тип отсеивает элементы, которые не могут определить причину сбоя системы. Это было добавлено в Windows 10 и особенно полезно, если вы используете виртуальную машину, или если ваша система является хостом Hyper-V.

Как включить создание дампа памяти в Windows?

С помощью Win+Pause откройте окно с параметрами системы, выберите «Дополнительные параметры системы» (Advanced system settings). Во вкладке «Дополнительно» (Advanced), раздел «Загрузка и восстановление» (Startup and Recovery) нажмите кнопку «Параметры» (Settings). В открывшемся окне настройте действия при отказе системы. Поставьте галку в чек-боксе «Записать события в системный журнал» (Write an event to the system log), выберите тип дампа, который должен создаваться при сбое системы. Если в чек-боксе «Заменять существующий файл дампа» (Overwrite any existing file) поставить галку, то файл будет перезаписываться при каждом сбое. Лучше эту галку снять, тогда у вас будет больше информации для анализа. Отключите также автоматическую перезагрузку системы (Automatically restart).

В большинстве случаев для анализа причины BSOD вам будет достаточно малого дампа памяти.

Теперь при возникновении BSOD вы сможете проанализировать файл дампа и найти причину сбоев. Мини дамп по умолчанию сохраняется в папке %systemroot%\minidump. Для анализа файла дампа рекомендую воспользоваться программой WinDBG (Microsoft Kernel Debugger).

Установка WinDBG в Windows

Утилита WinDBG входит в «Пакет SDK для Windows 10» (Windows 10 SDK). Скачать можно здесь.

Файл называется winsdksetup.exe, размер 1,3 МБ.

Запустите установку и выберите, что именно нужно сделать – установить пакет на этот компьютер или загрузить для установки на другие компьютеры. Установим пакет на локальный компьютер.

Можете установить весь пакет, но для установки только инструмента отладки выберите Debugging Tools for Windows.

После установки ярлыки WinDBG можно найти в стартовом меню.

Настройка ассоциации .dmp файлов с WinDBG

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

  1. Откройте командную строку от имени администратора и выполните команды для 64-разрядной системы: cd C:\Program Files (x86)\Windows Kits\10\Debuggers\x64
    windbg.exe –IA
    для 32-разрядной системы:
    C:\Program Files (x86)\Windows Kits\10\Debuggers\x86
    windbg.exe –IA
  2. В результате типы файлов: .DMP, .HDMP, .MDMP, .KDMP, .WEW – будут сопоставлены с WinDBG.

Настройка сервера отладочных символов в WinDBG

Отладочные символы (debug-символы или symbol files) – это блоки данных, генерируемые в процессе компиляции программы совместно с исполняемым файлом. В таких блоках данных содержится информация о именах переменных, вызываемых функциях, библиотеках и т.д. Эти данные не нужны при выполнении программы, но полезные при ее отладке. Компоненты Microsoft компилируются с символами, распространяемыми через Microsoft Symbol Server.

Настройте WinDBG на использование Microsoft Symbol Server:

  • Откройте WinDBG;
  • Перейдите в меню File –>Symbol File Path;
  • Пропишите строку, содержащую URL для загрузки символов отладки с сайта Microsoft и папку для сохранения кэша: SRV*E:\Sym_WinDBG*http://msdl.microsoft.com/download/symbols В примере кэш загружается в папку E:\Sym_WinDBG, можете указать любую.
  • Не забывайте сохранить изменения в меню File –>Save WorkSpace;
Читайте также:  Create program launcher windows

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

Если подключение к интернету отсутствует, то загрузите предварительно пакет символов с ресурса Windows Symbol Packages.

Анализ аварийного дампа памяти в WinDBG

Отладчик WinDBG открывает файл дампа и загружает необходимые символы для отладки из локальной папки или из интернета. Во время этого процесса вы не можете использовать WinDBG. Внизу окна (в командной строке отладчика) появляется надпись Debugee not connected.

Команды вводятся в командную строку, расположенную внизу окна.

Самое главное, на что нужно обратить внимание – это код ошибки, который всегда указывается в шестнадцатеричном значении и имеет вид 0xXXXXXXXX (указываются в одном из вариантов — STOP: 0x0000007B, 02.07.2019 0008F, 0x8F). В нашем примере код ошибки 0х139.

Отладчик предлагает выполнить команду !analyze -v, достаточно навести указатель мыши на ссылку и кликнуть. Для чего нужна эта команда?

  • Она выполняет предварительный анализ дампа памяти и предоставляет подробную информацию для начала анализа.
  • Эта команда отобразит STOP-код и символическое имя ошибки.
  • Она показывает стек вызовов команд, которые привели к аварийному завершению.
  • Кроме того, здесь отображаются неисправности IP-адреса, процессов и регистров.
  • Команда может предоставить готовые рекомендации по решению проблемы.

Основные моменты, на которые вы должны обратить внимание при анализе после выполнения команды !analyze –v (листинг неполный).

*****************************************************************************
* *
* Bugcheck Analysis *
* *
*****************************************************************************
Символическое имя STOP-ошибки (BugCheck)
KERNEL_SECURITY_CHECK_FAILURE (139)
Описание ошибки (Компонент ядра повредил критическую структуру данных. Это повреждение потенциально может позволить злоумышленнику получить контроль над этой машиной):

A kernel component has corrupted a critical data structure. The corruption could potentially allow a malicious user to gain control of this machine.
Аргументы ошибки:

Arguments:
Arg1: 0000000000000003, A LIST_ENTRY has been corrupted (i.e. double remove).
Arg2: ffffd0003a20d5d0, Address of the trap frame for the exception that caused the bugcheck
Arg3: ffffd0003a20d528, Address of the exception record for the exception that caused the bugcheck
Arg4: 0000000000000000, Reserved
Debugging Details:
——————

Счетчик показывает сколько раз система упала с аналогичной ошибкой:

Основная категория текущего сбоя:

Код STOP-ошибки в сокращенном формате:

Процесс, во время исполнения которого произошел сбой (не обязательно причина ошибки, просто в момент сбоя в памяти выполнялся этот процесс):

Расшифровка кода ошибки: В этом приложении система обнаружила переполнение буфера стека, что может позволить злоумышленнику получить контроль над этим приложением.

ERROR_CODE: (NTSTATUS) 0xc0000409 — The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.
EXCEPTION_CODE: (NTSTATUS) 0xc0000409 — The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.

Последний вызов в стеке:

LAST_CONTROL_TRANSFER: from fffff8040117d6a9 to fffff8040116b0a0

Стек вызовов в момент сбоя:

STACK_TEXT:
ffffd000`3a20d2a8 fffff804`0117d6a9 : 00000000`00000139 00000000`00000003 ffffd000`3a20d5d0 ffffd000`3a20d528 : nt!KeBugCheckEx
ffffd000`3a20d2b0 fffff804`0117da50 : ffffe000`f3ab9080 ffffe000`fc37e001 ffffd000`3a20d5d0 fffff804`0116e2a2 : nt!KiBugCheckDispatch+0x69
ffffd000`3a20d3f0 fffff804`0117c150 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!KiFastFailDispatch+0xd0
ffffd000`3a20d5d0 fffff804`01199482 : ffffc000`701ba270 ffffc000`00000001 000000ea`73f68040 fffff804`000006f9 : nt!KiRaiseSecurityCheckFailure+0x3d0
ffffd000`3a20d760 fffff804`014a455d : 00000000`00000001 ffffd000`3a20d941 ffffe000`fcacb000 ffffd000`3a20d951 : nt! ?? ::FNODOBFM::`string’+0x17252
ffffd000`3a20d8c0 fffff804`013a34ac : 00000000`00000004 00000000`00000000 ffffd000`3a20d9d8 ffffe001`0a34c600 : nt!IopSynchronousServiceTail+0x379
ffffd000`3a20d990 fffff804`0117d313 : ffffffff`fffffffe 00000000`00000000 00000000`00000000 000000eb`a0cf1380 : nt!NtWriteFile+0x694
ffffd000`3a20da90 00007ffb`475307da : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!KiSystemServiceCopyEnd+0x13
000000ee`f25ed2b8 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : 0x00007ffb`475307da

Участок кода, где возникла ошибка:

FOLLOWUP_IP:
nt!KiFastFailDispatch+d0
fffff804`0117da50 c644242000 mov byte ptr [rsp+20h],0
FAULT_INSTR_CODE: 202444c6
SYMBOL_STACK_INDEX: 2
SYMBOL_NAME: nt!KiFastFailDispatch+d0
FOLLOWUP_NAME: MachineOwner

Имя модуля в таблице объектов ядра. Если анализатору удалось обнаружить проблемный драйвер, имя отображается в полях MODULE_NAME и IMAGE_NAME:

MODULE_NAME: nt
IMAGE_NAME: ntkrnlmp.exe

Если кликнете по ссылке модуля (nt), то увидите подробную информацию о пути и других свойствах модуля. Находите указанный файл, и изучаете его свойства.

1: kd> lmvm nt
Browse full module list
Loaded symbol image file: ntkrnlmp.exe
Mapped memory image file: C:\ProgramData\dbg\sym\ntoskrnl.exe\5A9A2147787000\ntoskrnl.exe
Image path: ntkrnlmp.exe
Image name: ntkrnlmp.exe
InternalName: ntkrnlmp.exe
OriginalFilename: ntkrnlmp.exe
ProductVersion: 6.3.9600.18946
FileVersion: 6.3.9600.18946 (winblue_ltsb_escrow.180302-1800)

В приведенном примере анализ указал на файл ядра ntkrnlmp.exe. Когда анализ дампа памяти указывает на системный драйвер (например, win32k.sys) или файл ядра (как в нашем примере ntkrnlmp.exe), вероятнее всего данный файл не является причиной проблемы. Очень часто оказывается, что проблема кроется в драйвере устройства, настройках BIOS или в неисправности оборудования.

Если вы увидели, что BSOD возник из-за стороннего драйвера, его имя будет указано в значениях MODULE_NAME и IMAGE_NAME.

Image path: \SystemRoot\system32\drivers\cmudaxp.sys
Image name: cmudaxp.sys

Откройте свойсва файла драйвера и проверьте его версию. В большинстве случаев проблема с драйверами решается их обнвовлением.

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