/dsc/index.py

https://github.com/Yell0wra1n/star
Python | 73 lines | 68 code | 5 blank | 0 comment | 23 complexity | e6d98a14fd1dce9012b509b8444676f1 MD5 | raw file
  1. import struct, anydbm, sys, glob
  2. def build(path):
  3. db = anydbm.open('index', 'c')
  4. files = glob.glob('%s/*.txt' % path)
  5. db['_files'] = '\0'.join(files)
  6. for fil in files:
  7. lineno = 1
  8. fileoff = 0
  9. for line in open(fil, 'rb'):
  10. scratch = line[:6]
  11. try:
  12. key = int(line[:6], 16)
  13. except:
  14. if ':' in line:
  15. key = '\0\0\0\0' + line[:line.find(':')]
  16. db[key] = struct.pack('III', files.index(fil), lineno, fileoff)
  17. else:
  18. key = struct.pack('I', key)
  19. if not db.has_key(key):
  20. db[key] = struct.pack('III', files.index(fil), lineno, fileoff)
  21. lineno += 1
  22. fileoff += len(line)
  23. def ful(fp):
  24. ret = ''
  25. while True:
  26. ln = fp.readline()
  27. ret += ln
  28. if ln == '' or 'pop\t' in ln: break
  29. return ret
  30. def lookup_sym(sym, full=False):
  31. db = anydbm.open('index')
  32. files = db['_files'].split('\0')
  33. key = '\0\0\0\0' + sym
  34. try:
  35. fili, line, filoff = struct.unpack('III', db[key])
  36. except KeyError:
  37. return None
  38. fp = open(files[fili], 'rb')
  39. fp.seek(filoff)
  40. if full: return ful(fp).rstrip()
  41. return '[%s:%d] %s %s' % (files[fili], line, fp.readline().strip(), fp.readline().strip())
  42. def lookup_addr(addr, full=False):
  43. db = anydbm.open('index')
  44. files = db['_files'].split('\0')
  45. addr &= ~1
  46. key = struct.pack('I', int(addr) / 0x100)
  47. try:
  48. fili, line, filoff = struct.unpack('III', db[key])
  49. except KeyError:
  50. return None
  51. fp = open(files[fili], 'rb')
  52. fp.seek(filoff)
  53. q = '%08x' % addr
  54. lineno = line
  55. while True:
  56. line = fp.readline()
  57. if line[:8] == q:
  58. if full: return (line + ful(fp)).rstrip()
  59. return '[%s:%d] %s' % (files[fili], lineno, line.strip())
  60. elif line == '':
  61. return None
  62. lineno += 1
  63. if sys.argv[1] == 'build':
  64. build(sys.argv[2])
  65. elif sys.argv[1] == 'sym':
  66. print lookup_sym(sys.argv[2], len(sys.argv) > 3 and sys.argv[3] == 'full')
  67. else:
  68. print lookup_addr(int(sys.argv[1], 16), len(sys.argv) > 2 and sys.argv[2] == 'full')