Windows program crash dump

Чем открыть файл дампа памяти Windows MEMORY.DMP

Многие знакомы с «синим экраном смерти» или BlueScreen. Синий экран появляется когда в работе Windows возникает критическая ошибка, что приводит к остановке работы операционной системы. При этом операционная система создает дамп памяти, в который записывает отладочную информацию и добавляет запись в журнал событий.

В Windows существуют два типа дампа памяти — малый дамп (minidump) и полный дамп.
Minidump находится в директории C:\Windows\Minidump и его название имеет примерно такой вид Mini051819-01.dmp.
Полный дамп располагается в папке C:\Windows и называется MEMORY.DMP.

Просмотр и анализ файла минидампа.

Для просмотра и анализа файла минидампа можно воспользоваться достаточно простой и удобной утилитой BlueScreenView от Nirsoft, которую можно скачать с официального сайта https://www.nirsoft.net/utils/blue_screen_view.html .

Для просмотра минидампа достаточно перетащить файл в окно программы и тут же загрузится отладочная информация. Красным будут подсвечены модули вызвавшие ошибку. В случае представленном на скриншоте выше это был драйвер tcpip.sys.

Щелкнув по имени файла минидампа можно запустить поиск решения в Google.

Но эта программа не способна обработать полный дамп памяти Windows — memory.dmp.

Просмотр полного дампа памяти MEMORY.DMP.

Чтобы посмотреть содержимое полного дампа памяти необходимо открыть файл MEMORY.DMP при помощи утилиты WinDBG, которая входит в пакет Microsoft Windows SDK. Скачать эту утилиту можно с официального сайта Майкрософт по этой ссылке https://developer.microsoft.com/ru-ru/windows/downloads/windows-10-sdk .

Установка и настройка WinDBG.

Запускаем установку пакета Windows Software Development KIT и на этапе выбора компонентов отмечаем «Debugging Tools for Windows».

При первом запуске WinDBG необходимо выполнить настройку сервера отладочных символов.
1. Переходим в меню File > Symbol File Path и вставляем строку:

где C:\symbol_cache — это директория куда будут загружаться символы.

2. Сохраняем настройку File > Save Workspace.

Просмотр и анализ файла MEMORY.DMP.

Открываем файл MEMORY.DMP: File > Open Crash Dump. Начинается процесс загрузки отладочных символов, в этот момент внизу будет видна надпись: Debugee not connected.

По окончанию загрузки появится подсказка: «для анализа этого файла запустите !analize-v».

Щелкаем по надписи !analize-v и запускается анализ дампа. В этот момент в строке состояние будет надпись *BUSY*.

По завершении обработки файла дампа памяти Windows нам необходимо найти среди полученной информации модуль, который вызвал сбой в работе. Найти сбойный модуль можно в строках MODULE_NAME и IMAGE_NAME.

В моем случае произошел сбой в работе драйвера srv.sys. В строке MODULE_NAME имя представлено в виде ссылке, щелкнув по которому можно получить информацию о модуле.

После выявления драйвера послужившего причиной сбоя в работе Windows и появления «Синего экрана смерти» необходимо попытаться обновить его.

Большинство проблем с драйверами решаются их обновлением.

Generate a kernel or complete crash dump

A system crash (also known as a “bug check” or a «Stop error») occurs when Windows can’t run correctly. The dump file that is produced from this event is called a system crash dump.

A manual kernel or complete memory dump file is useful when you troubleshoot several issues because the process captures a record of system memory at the time of a crash.

Set up page files

See Support for system crash dumps for the page file size requirement for system crash dump.

Enable memory dump setting

You must be logged on as an administrator or a member of the Administrators group to complete this procedure. If your computer is connected to a network, network policy settings may prevent you from completing this procedure.

Читайте также:  Образ windows для parallels desktop

To enable memory dump setting, follow these steps:

In Control Panel, select System and Security > System.

Select Advanced system settings, and then select the Advanced tab.

In the Startup and Recovery area, select Settings.

Make sure that Kernel memory dump or Complete memory dump is selected under Writing Debugging Information.

Restart the computer.

You can change the dump file path by edit the Dump file field. In other words, you can change the path from %SystemRoot%\Memory.dmp to point to a local drive that has enough disk space, such as E:\Memory.dmp.

Tips to generate memory dumps

When the computer crashes and restarts, the contents of physical RAM are written to the paging file that is located on the partition on which the operating system is installed.

Depending on the speed of the hard disk on which Windows is installed, dumping more than 2 gigabytes (GB) of memory may take a long time. Even in a best case scenario, if the dump file is configured to reside on another local hard drive, a significant amount of data will be read and written to the hard disks. This can cause a prolonged server outage.

Use this method to generate complete memory dump files with caution. Ideally, you should do this only when you are explicitly requested to by the Microsoft Support engineer. Any kernel or complete memory dump file debugging should be the last resort after all standard troubleshooting methods have been completely exhausted.

Manually generate a memory dump file

Use the NotMyFault tool

If you can log on while the problem is occurring, you can use the Microsoft Sysinternals NotMyFault tool. To do this, follow these steps:

Download the NotMyFault tool.

Select Start, and then select Command Prompt.

At the command line, run the following command:

This operation generates a memory dump file and a D1 Stop error.

Use NMI

On some computers, you cannot use keyboard to generate a crash dump file. For example, Hewlett-Packard (HP) BladeSystem servers from the Hewlett-Packard Development Company are managed through a browser-based graphical user interface (GUI). A keyboard is not attached to the HP BladeSystem server.

In these cases, you must generate a complete crash dump file or a kernel crash dump file by using the Non-Maskable Interrupt (NMI) switch that causes an NMI on the system processor.

To do this, follow these steps:

Follow the steps in this section carefully. Serious problems might occur if you modify the registry incorrectly. Before you modify it, back up the registry for restoration in case problems occur.

In Registry Editor, locate the following registry subkey:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CrashControl

Right-click CrashControl, point to New, and then click DWORD Value.

Type NMICrashDump, and then press Enter.

Right-click NMICrashDump, and then select Modify.

In the Value data box, type 1, and then select OK.

Restart the computer.

Hardware vendors, such as HP, IBM, and Dell, may provide an Automatic System Recovery (ASR) feature. You should disable this feature during troubleshooting. For example, if the HP and Compaq ASR feature is enabled in the BIOS, disable this feature while you troubleshoot to generate a complete Memory.dmp file. For the exact steps, contact your hardware vendor.

Enable the NMI switch in the BIOS or by using the Integrated Lights Out (iLO) Web interface.

For the exact steps, see the BIOS reference manual or contact your hardware vendor.

Test this method on the server by using the NMI switch to generate a dump file. You will see a STOP 0x00000080 hardware malfunction.

If you want to run NMI in Microsoft Azure using Serial Console, see Use Serial Console for SysRq and NMI calls.

Crash Dump Analysis

Not all bugs can be found prior to release, which means not all bugs that throw exceptions can be found before release. Fortunately, Microsoft has included in the Platform SDK a function to help developers collect information on exceptions that are discovered by users. The MiniDumpWriteDump function writes the necessary crash dump information to a file without saving the whole process space. This crash dump information file is called a minidump. This technical article provides info about how to write and use a minidump.

Читайте также:  Проверка целостности ядра windows

Writing a Minidump

The basic options for writing a minidump are as follows:

Do nothing. Windows automatically generates a minidump whenever a program throws an unhandled exception. Automatic generation of a minidump is available since Windows XP. If the user allows it, the minidump will be sent to Microsoft, and not to the developer, through Windows Error Reporting (WER). Developers can gain access to these minidumps through the Windows Desktop Application Program.

Use of WER requires:

  • Developers to sign their applications using Authenticode
  • Applications have valid VERSIONINFO resource in every executable and DLL

If you implement a custom routine for unhandled exceptions, you are strongly urged to use the ReportFault function in the exception handler to also send an automated minidump to WER. The ReportFault function handles all of the issues of connecting to and sending the minidump to WER. Not sending minidumps to WER violates the requirements of Games for Windows.

For more information on how WER works, see How Windows Error Reporting Works. For an explanation of registration details, see Introducing Windows Error Reporting on MSDN’s ISV Zone.

Use a product from the Microsoft Visual Studio Team System. On the Debug menu, click Save Dump As to save a copy of a dump. Use of a locally saved dump is only an option for in-house testing and debugging.

Add code to your project. Add the MiniDumpWriteDump function and the appropriate exception handling code to save and send a minidump directly to the developer. This article demonstrates how to implement this option. However, note that MiniDumpWriteDump does not currently work with managed code and is only available on Windows XP, Windows Vista, Windows 7.

Thread safety

MiniDumpWriteDump is part of the DBGHELP library. This library is not thread-safe, so any program that uses MiniDumpWriteDump should synchronize all threads before attempting to call MiniDumpWriteDump.

Writing a Minidump with Code

The actual implementation is straightforward. The following is a simple example of how to use MiniDumpWriteDump.

This example demonstrates the basic usage of MiniDumpWriteDump and the minimum information necessary to call it. The name of the dump file is up to the developer; however, to avoid file name collisions, it is advisable to generate the file name from the application’s name and version number, the process and thread IDs, and the date and time. This will also help to keep the minidumps grouped by application and version. It is up to the developer to decide how much information is used to differentiate minidump file names.

It should be noted that the path name in the preceding example was generated by calling the GetTempPath function to retrieve the path of the directory designated for temporary files. Use of this directory works even with least-privileged user accounts, and it also prevents the minidump from taking up hard drive space after it is no longer needed.

If you archive the product during your daily build process, also be sure to include symbols for the build so that you can debug an old version of the product, if necessary. You also need to take steps to maintain full compiler optimizations while generating symbols. This can be done by opening your project’s properties in the development environment and, for the release configuration, doing the following:

  1. On the left side of the project’s property page, click C/C++. By default, this displays General settings. On the right side of the project’s property page, set Debug Information Format to Program Database (/Zi).
  2. On the left side of the property page, expand Linker, and then click Debugging. On the right side of the property page, set Generate Debug Info to Yes (/DEBUG).
  3. Click Optimization, and set References to Eliminate Unreferenced Data (/OPT:REF).
  4. Set Enable COMDAT Folding to Remove Redundant COMDATs (/OPT:ICF).
Читайте также:  Как полностью обнулить компьютер до заводских настроек windows 10

Using Dumpchk.exe

Dumpchk.exe is a command-line utility that can be used to verify that a dump file was created correctly. If Dumpchk.exe generates an error, then the dump file is corrupt and cannot be analyzed. For information on using Dumpchk.exe, see How to Use Dumpchk.exe to Check a Memory Dump File.

Dumpchk.exe is included on the Windows XP product CD and can be installed to System Drive\Program Files\Support Tools\ by running Setup.exe in the Support\Tools\ folder on the Windows XP product CD. You can also get the latest version of Dumpchk.exe by download and installing the debugging tools available from Windows Debugging Tools on Windows Hardware Developer Central.

Analyzing a Minidump

Opening a minidump for analysis is as easy as creating one.

To analyze a minidump

  1. Open Visual Studio.
  2. On the File menu, click Open Project.
  3. Set Files of type to Dump Files, navigate to the dump file, select it, and click Open.
  4. Run the debugger.

The debugger will create a simulated process. The simulated process will be halted at the instruction that caused the crash.

Using the Microsoft Public Symbol Server

To get the stack for driver- or system-level crashes, it might be necessary to configure Visual Studio to point to the Microsoft public symbol server.

To set a path to the Microsoft symbol server

  1. On the Debug menu, click Options.
  2. In the Options dialog box, open the Debugging node, and click Symbols.
  3. Make sure Search the above locations only when symbols are loaded manually is not selected, unless you want to load symbols manually when you debug.
  4. If you are using symbols on a remote symbol server, you can improve performance by specifying a local directory that symbols can be copied to. To do this, enter a path for Cache symbols from symbol server to this directory. To connect to the Microsoft public symbol server, you need to enable this setting. Note that if you are debugging a program on a remote computer, the cache directory refers to a directory on the remote computer.
  5. Click OK.
  6. Because you are using the Microsoft public symbol server, an End User License Agreement dialog box appears. Click Yes to accept the agreement and download symbols to your local cache.

Debugging a Minidump with WinDbg

You can also use WinDbg, a debugger that is part of the Windows Debugging Tools, to debug a minidump. WinDbg allows you to debug without having to use Visual Studio. To download Windows Debugging Tools, see Windows Debugging Tools on Windows Hardware Developer Central.

After installing Windows Debugging Tools, you must enter the symbol path in WinDbg.

To enter a symbol path in WinDbg

On the File menu, click Symbol Path.

In the Symbol Search Path window, enter the following:

Using Copy-Protection Tools with Minidumps

Developers also need to be aware of how their copy-protection scheme might affect the minidump. Most copy-protection schemes have their own descramble tools, and it is up to the developer to learn how to use those tools with MiniDumpWriteDump.

Summary

The MiniDumpWriteDump function can be an extremely useful tool in collecting and solving bugs after the product has been released. Writing a custom exception handler that uses MiniDumpWriteDump allows the developer to customize the information collection and improve the debugging process. The function is flexible enough to be used in any C++-based project and should be considered part of any project’s stability process.

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