You are currently browsing the archives for the Programming category


WinDbg Extension – GetOffsetByName

In this post I would like to explain with a working example the sematics of the GetOffsetByName from IDebugSymbols interface in WinDbg Extension API.

  1. You can use this method to return the offset of a symbol that is in the data segment but not on the heap. Data segment is the place in the program where global variables are stored. If you try to get the offset of a field of a class instance (object) this will not work (e.g. instanceOfMyClass->fieldName).
  2. The value that this method returns as offset is address of the global variable i.e. &var. Lets explain with an example.

On the running example I assuming

class MyClass {

static int staticField.

};

myext.getoffsetbyname is the custom extension that implements GetOffsetByName

Then if we un the following commands in WinDbg command window

0:000:x86> x simple!MyClass::staticField

0x004d81e4 simple!MyClass::staticField = 0x00000005

0:000:x86> ?? &(MyClass::staticField)

class MyClass[] ** 0x004d81e4

0:000:x86> !tm.rset simple!MyClass::staticField

Symbol Offset: 0x004d81e4

0:000:x86> dd 0x004d81e4 L1

0x004d81e4 0x00000005


Address

Variable Name

Value

004d81e4 (&MyClass::staticField)

MyClass::staticField

0x00000005(value = 5)

And the file implementing the extension is given below. To build the code refer to Building DbgEng Extensions.

class EXT_CLASS : public ExtExtension {

public:

EXT_DECLARE_METHOD(getoffsetbyname);

};

EXT_DECLARE_GLOBALS();

EXT_COMMAND(getoffsetbyname,

“Prints the offset of a symbol.”,

“{;s,o,d=simple!MyData::staticField;symb;Symbol Name}”)

{

Out(“nReadset:n”);

HRESULT isOk = E_FAIL;

IDebugSymbols *symbols = this->m_Symbols;

PCSTR arg = GetUnnamedArgStr(0);

ULONG64 chunkOffset = 0;

isOk = symbols->GetOffsetByName(arg, &chunkOffset);

if (isOk == S_OK) {

Out(“Symbol Offset: %08x – %lun”, chunkOffset, chunkOffset);

}

else if (isOk == S_FALSE) {

Out(“Symbol Offset (many found): %08x – %lun”, chunkOffset, chunkOffset);

}

else {

Out(“Error: Symbol Offsetn”);

}

}