/Tools/scripts/nm2def.py

http://unladen-swallow.googlecode.com/ · Python · 103 lines · 61 code · 6 blank · 36 comment · 5 complexity · d25314b59bd26643cf6d2728af711037 MD5 · raw file

  1. #! /usr/bin/env python
  2. """nm2def.py
  3. Helpers to extract symbols from Unix libs and auto-generate
  4. Windows definition files from them. Depends on nm(1). Tested
  5. on Linux and Solaris only (-p option to nm is for Solaris only).
  6. By Marc-Andre Lemburg, Aug 1998.
  7. Additional notes: the output of nm is supposed to look like this:
  8. acceler.o:
  9. 000001fd T PyGrammar_AddAccelerators
  10. U PyGrammar_FindDFA
  11. 00000237 T PyGrammar_RemoveAccelerators
  12. U _IO_stderr_
  13. U exit
  14. U fprintf
  15. U free
  16. U malloc
  17. U printf
  18. grammar1.o:
  19. 00000000 T PyGrammar_FindDFA
  20. 00000034 T PyGrammar_LabelRepr
  21. U _PyParser_TokenNames
  22. U abort
  23. U printf
  24. U sprintf
  25. ...
  26. Even if this isn't the default output of your nm, there is generally an
  27. option to produce this format (since it is the original v7 Unix format).
  28. """
  29. import os, sys
  30. PYTHONLIB = 'libpython'+sys.version[:3]+'.a'
  31. PC_PYTHONLIB = 'Python'+sys.version[0]+sys.version[2]+'.dll'
  32. NM = 'nm -p -g %s' # For Linux, use "nm -g %s"
  33. def symbols(lib=PYTHONLIB,types=('T','C','D')):
  34. lines = os.popen(NM % lib).readlines()
  35. lines = [s.strip() for s in lines]
  36. symbols = {}
  37. for line in lines:
  38. if len(line) == 0 or ':' in line:
  39. continue
  40. items = line.split()
  41. if len(items) != 3:
  42. continue
  43. address, type, name = items
  44. if type not in types:
  45. continue
  46. symbols[name] = address,type
  47. return symbols
  48. def export_list(symbols):
  49. data = []
  50. code = []
  51. for name,(addr,type) in symbols.items():
  52. if type in ('C','D'):
  53. data.append('\t'+name)
  54. else:
  55. code.append('\t'+name)
  56. data.sort()
  57. data.append('')
  58. code.sort()
  59. return ' DATA\n'.join(data)+'\n'+'\n'.join(code)
  60. # Definition file template
  61. DEF_TEMPLATE = """\
  62. EXPORTS
  63. %s
  64. """
  65. # Special symbols that have to be included even though they don't
  66. # pass the filter
  67. SPECIALS = (
  68. )
  69. def filter_Python(symbols,specials=SPECIALS):
  70. for name in symbols.keys():
  71. if name[:2] == 'Py' or name[:3] == '_Py':
  72. pass
  73. elif name not in specials:
  74. del symbols[name]
  75. def main():
  76. s = symbols(PYTHONLIB)
  77. filter_Python(s)
  78. exports = export_list(s)
  79. f = sys.stdout # open('PC/python_nt.def','w')
  80. f.write(DEF_TEMPLATE % (exports))
  81. f.close()
  82. if __name__ == '__main__':
  83. main()