编辑:下面的答案特定于 PE 文件,现在@Achilles 指定他的问题与 ELF 文件有关,因此它没有回答上面的问题。
鉴于您拥有源代码并且可以为您的程序生成符号,您可以使用调试接口访问 SDK将汇编代码指令地址映射到源代码行号。特别是,您可能想要使用IDiaLineNumber 类。
以下函数显示函数中使用的行号(由 表示pSymbol
)。
void dumpFunctionLines( IDiaSymbol* pSymbol, IDiaSession* pSession ) {
ULONGLONG length = 0;
DWORD isect = 0;
DWORD offset = 0;
pSymbol->get_addressSection( &isect );
pSymbol->get_addressOffset( &offset );
pSymbol->get_length( &length );
if ( isect != 0 && length > 0 )
{
CComPtr< IDiaEnumLineNumbers > pLines;
if ( SUCCEEDED( pSession->findLinesByAddr(
isect,
offset,
static_cast<DWORD>( length ),
&pLines)
)
)
{
CComPtr< IDiaLineNumber > pLine;
DWORD celt = 0;
bool firstLine = true;
while ( SUCCEEDED( pLines->Next( 1, &pLine, &celt ) ) &&
celt == 1 )
{
DWORD offset;
DWORD seg;
DWORD linenum;
CComPtr< IDiaSymbol > pComp;
CComPtr< IDiaSourceFile > pSrc;
pLine->get_compiland( &pComp );
pLine->get_sourceFile( &pSrc );
pLine->get_addressSection( &seg );
pLine->get_addressOffset( &offset );
pLine->get_lineNumber( &linenum );
printf( "\tline %d at 0x%x:0x%x\n", linenum, seg, offset );
pLine = NULL;
if ( firstLine )
{
// sanity check
CComPtr< IDiaEnumLineNumbers > pLinesByLineNum;
if ( SUCCEEDED( pSession->findLinesByLinenum(
pComp,
pSrc,
linenum,
0,
&pLinesByLineNum)
)
)
{
CComPtr< IDiaLineNumber > pLine;
DWORD celt;
while ( SUCCEEDED( pLinesByLineNum->Next( 1, &pLine, &celt ) ) &&
celt == 1 )
{
DWORD offset;
DWORD seg;
DWORD linenum;
pLine->get_addressSection( &seg );
pLine->get_addressOffset( &offset );
pLine->get_lineNumber( &linenum );
printf( "\t\tfound line %d at 0x%x:0x%x\n", linenum, seg, offset );
pLine = NULL;
}
}
firstLine = false;
}
}
}
} }