Python腳本在使用gdb調(diào)試時(shí)常會(huì)遇到的三個(gè)“克星”
使用gdb調(diào)試Python腳本
我們?cè)趯?shí)際調(diào)試python腳本中一般可以用記錄log和python本身自帶的pdb,當(dāng)然這是在一般的情況下,以下的文章就會(huì)提出一些運(yùn)用log和python本身自帶的pdb卻不能解決的相關(guān)情況的相關(guān)介紹。 但凡事總有例外,在以下三種情況時(shí)上述方法就無(wú)能為力了。
1 段錯(cuò)誤
2 運(yùn)行中的daemon程序
3 core dump
這個(gè)時(shí)候就需祭出gdb進(jìn)行調(diào)試。python2.6的源碼中提供了部分預(yù)定義函數(shù)以便大家使用gdb調(diào)試,我們只需將文件Python-2.6/Misc/gdbinit所包括的內(nèi)容加入到用戶目錄下的.gdbinit文件中即可,這樣每次啟動(dòng)gdb時(shí)會(huì)自動(dòng)完成這些宏的定義。但可惜的是Python2.6.2 gdbini對(duì)于pylocals的定義居然有錯(cuò)誤, 看來(lái)是沒有隨著代碼的更新而同步更新。
我們只需將
- while $_i < f->f_nlocals
修改為
- while $_i < f->f_code->co_nlocals
即可。文章后面所附的幾個(gè)宏建議也加入的.gdbinit文件中,更多的宏可參考我們首先需要構(gòu)造一個(gè)會(huì)造成段錯(cuò)誤的python腳本。老實(shí)說(shuō)讓python發(fā)生段錯(cuò)誤并不容易,但通過(guò)其外部調(diào)用庫(kù)就很簡(jiǎn)單了。我們將該文件命名為gdb_test.py
- import sys, os, libxml2
- def segv_test():
- s = "<html><body><div><a><a></a></a><a></a></div></body></html>"
- options = libxml2.HTML_PARSE_RECOVER + \
- libxml2.HTML_PARSE_NOERROR + \
- libxml2.HTML_PARSE_NOWARNING
- doc = libxml2.htmlReadDoc(s, None, 'utf-8', options).doc
- ctxt = doc.xpathNewContext()
- nodes = ctxt.xpathEval('//body/node()')
- nodes.reverse()
- for note in nodes:
- nexts = note.xpathEval('node()')
- note.unlinkNode()
- note.freeNode()
freeNode會(huì)將該節(jié)點(diǎn)及其子節(jié)點(diǎn)釋放掉
- nexts[0].unlinkNode()
- nexts[0].freeNode()
資源已經(jīng)釋放,再次釋放會(huì)造成段錯(cuò)誤
- def main():
- segv_test()
- if __name__ == "__main__":
- main()
使用gdb運(yùn)行該腳本,我們會(huì)得到段錯(cuò)誤信息。
- gdb python
- r gdb_test.py
- *** glibc detected *** double free or corruption
(fasttop): 0x08104570 ***- Program received signal SIGABRT, Aborted.
- [Switching to Thread -1208260928 (LWP 26159)]
- 0x00b987a2 in _dl_sysinfo_int80 () from /
lib/ld-linux.so.2
以上就是對(duì)使用gdb調(diào)試Python腳本相關(guān)的內(nèi)容的介紹,望你會(huì)有所收獲。
【編輯推薦】