GDB/FreePascal – How a debugger can trigger on variable corruption

Problem: Some variable is overwritten in your program and you need to find the location where this will happen.

Example: As you can see from the program output, the variable ‘otherdata’ has been corrupted by the variable ‘data. Imagine, between the corruption and using again the variable ‘otherdata’ million of code lines could be executed!

program project1;
type p64 = ^int64;

procedure testme;
var
  otherdata: integer;
  data: integer;
begin
  writeln('data=',hexStr(data, 8));
  writeln('otherdata=',hexStr(otherdata, 8));
  writeln;

  p64(@data)^:=$00AABBBBCCCCDDDD;  // overwrites otherdata
  writeln('dummy');
  writeln('dummy');
  writeln('data=',hexStr(data, 8));
  writeln('otherdata=',hexStr(otherdata, 8));
end;

begin
  testme();
end.

C:Projectsfrtestdebugger>project1.exe

data=7FFDB000
otherdata=0042C294
dummy
dummy
data=CCCCDDDD
otherdata=00AABBBB


Solution:
GDB has the ability to ‘watch‘ for variable changes and trigger them! In this example, it will stop execution at the line that corrupts the OTHERDATA variable.

C:\Projects\fr\test\debugger>gdb project1.exe

GNU gdb 6.8
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type “show copying”
and “show warranty” for details.
This GDB was configured as “i686-pc-mingw32″…
(gdb)

(gdb) break TESTME
Breakpoint 1 at 0x4014ff: file project1.lpr, line 23.

Breakpoint 1, TESTME () at project1.lpr:23
23        writeln(‘data=’,hexStr(data, 8));

(gdb) watch OTHERDATA
Hardware watchpoint 2: OTHERDATA

(gdb) continue
Continuing.
data=7FFDC000
otherdata=0042C294

Hardware watchpoint 2: OTHERDATA

Old value = 4375188
New value = 11189179
TESTME () at project1.lpr:27
27        writeln(‘dummy’);

Hopefully this feature will get into Lazarus soon 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

IMPORTANT! To be able to proceed, please enter the magic word 'endaag' so we know hat you are a human)

Enter the magic word:
Please leave these two fields as-is: