Using Page Heap Verification to Locate Heap Allocation Bugs

The program code below has a heap overflow bug. The memory location referenced by lpHeapVar1 is allocated one byte, but the subsequent code attempts to fill it with ten bytes of data, thus overflowing it.

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

int main(int argc, char **argv) {
    char stackVar[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    char *lpHeapVar1, *lpHeapVar2;
    printf("before allocating heap 1\n");
    lpHeapVar1 = (char *) malloc(1);
    printf("after allocating heap 1\n");
    printf("before overflowing heap 1\n");
    memcpy(lpHeapVar1, &stackVar, 10); // heap overflow
    printf("after overflowing heap 1\n");
    // other code here
    printf("before allocating heap 2\n");
    lpHeapVar2 = (char *) malloc(1);
    printf("after allocating heap 2\n");
    return 0;
}

When the program code above is compiled and run, it will crash at the following line of code.

lpHeapVar2 = (char *) malloc(1);

However, there is nothing wrong with the second malloc call itself. This makes the bug difficult to track down, even if a heap overflow is suspected to be the cause, especially if many lines of code separate the point of overflow and the subsequent heap allocation.

Page heap verification can help to track down such bugs. GFlags (included with Debugging Tools for Windows) is used to enable page heap verification.

C:\> gflags.exe -p /enable heap_allocate.exe /full
path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
    heap_allocate.exe: page heap enabled

where heap_allocate.exe is the compiled executable file.

Subsequently, when the program is run, it will crash at the point of the heap overflow (the memcpy function call).

References

[1] https://msdn.microsoft.com/en-us/library/windows/hardware/ff549566%28v=vs.85%29.aspx

Advertisements

Adding Album Cover to a FLAC File

When converting a wave file to a FLAC file using the flac command, an album cover can also be added by using the –picture argument with an input image file.

$ flac -0 ... --picture="3|image/jpeg|||cover.jpg" ... filename.wav

where 3 means that the picture is a front cover, cover.jpg is the cover image file, and filename.wav is the name of the input wave file.

Alternatively, metaflac can be used to add an album cover to a FLAC file.

$ metaflac --import-picture-from="3|image/jpeg|||cover.jpg" filename.flac

where the format of the –import-picture-from argument follows the –picture argument of the flac command, and filename.flac is the name of the FLAC file to be processed.

Note: flac and metaflac may not be present in a default installation. It can be installed through the package manager.

References

[1] https://sharpbang.wordpress.com/2013/08/07/converting-a-wave-file-to-a-flac-file/
[2] http://linux.die.net/man/1/flac
[3] http://linux.die.net/man/1/metaflac
[4] https://www.xiph.org/vorbis/doc/v-comment.html