xpathleak.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/python
  2. import sys, libxml2
  3. libxml2.debugMemory(True)
  4. expect="""--> Invalid expression
  5. --> xmlXPathEval: evaluation failed
  6. --> Invalid expression
  7. --> xmlXPathEval: evaluation failed
  8. --> Invalid expression
  9. --> xmlXPathEval: evaluation failed
  10. --> Invalid expression
  11. --> xmlXPathEval: evaluation failed
  12. --> Invalid expression
  13. --> xmlXPathEval: evaluation failed
  14. --> Invalid expression
  15. --> xmlXPathEval: evaluation failed
  16. --> Invalid expression
  17. --> xmlXPathEval: evaluation failed
  18. --> Invalid expression
  19. --> xmlXPathEval: evaluation failed
  20. --> Invalid expression
  21. --> xmlXPathEval: evaluation failed
  22. --> Invalid expression
  23. --> xmlXPathEval: evaluation failed
  24. """
  25. err=""
  26. def callback(ctx, str):
  27. global err
  28. err = err + "%s %s" % (ctx, str)
  29. libxml2.registerErrorHandler(callback, "-->")
  30. doc = libxml2.parseDoc("<fish/>")
  31. ctxt = doc.xpathNewContext()
  32. ctxt.setContextNode(doc)
  33. badexprs = (
  34. ":false()", "bad:()", "bad(:)", ":bad(:)", "bad:(:)", "bad:bad(:)",
  35. "a:/b", "/c:/d", "//e:/f", "g://h"
  36. )
  37. for expr in badexprs:
  38. try:
  39. ctxt.xpathEval(expr)
  40. except libxml2.xpathError, e:
  41. pass
  42. else:
  43. print "Unexpectedly legal expression:", expr
  44. ctxt.xpathFreeContext()
  45. doc.freeDoc()
  46. if err != expect:
  47. print "error"
  48. print "received %s" %(err)
  49. print "expected %s" %(expect)
  50. sys.exit(1)
  51. libxml2.cleanupParser()
  52. leakedbytes = libxml2.debugMemory(True)
  53. if leakedbytes == 0:
  54. print "OK"
  55. else:
  56. print "Memory leak", leakedbytes, "bytes"
  57. # drop file to .memdump file in cwd, but won't work if not compiled in
  58. libxml2.dumpMemory()