Enabling access violation to cause immediate crashing on Windows

From Site
Jump to: navigation, search

This is a must-have technique for developing in C++ under Windows.

Use the Microsoft utility gflags to have all heap accesses checked for bounds (that is: when you allocate arrays using the new keyword or malloc(..) or its variations). The system does everything — all you have to do is to register your file once. Then if there is some out-of-bounds access, your application will crash immediately and tell you "Your.exe has stopped working" with details such as

Problem signature:
 Problem Event Name:    AutoVerifier
 Application Name:      Your.exe
 Application Version:   0.0.0.0
 Application Timestamp: 4bf3d54c
 ...

Contents

Set the flag

Do this in an adminstrative Command Prompt (Shift+Right-click Command Prompt, then choose Run as administrator).

C:\Programs\DebuggingToolsForWindowsx86> ^
 gflags.exe -p /enable C:\Path\To\Your.exe /full

It will say

path: SOFTWARE\Microsoft\Windows NT\
CurrentVersion\Image File Execution Options
   Your.exe: page heap enabled

Then if you say

C:\Programs\DebuggingToolsForWindowsx86>gflags.exe -p

It will say

path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\
Image File Execution Options
   Your.exe: page heap enabled with flags (full traces )

Now what?

Now you can run it in a debugger, wait for the crash, and examine the traces for each thread to see where the bug is

In gdb

(gdb) thread apply all bt

To get this to work, compile the program with the -g flag, then use gdb like this:

$ g++ -g Your.cpp -o Your.exe
$ gdb Your.exe
$ (gdb) r

In WinDbg

In WinDbg, select File | Open Executable..., and don't forget to set the working directory. Type ~ to list threads. Type ~0 kp to see the stack of thread 0. If you encounter any first chance exceptions, type g to ignore them (we are only interested in second chance exceptions — those that are not caught before they crash the program).

In gdb type help, and in WinDbg type ? to get a list of commands available to you.

How is this implemented?

I don't know exactly. I don't even know if this is probabilistic or deterministic.