readtree.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env python3
  2. import struct
  3. import sys
  4. import json
  5. import io
  6. import itertools as it
  7. from readmdir import Tag, MetadataPair
  8. def popc(x):
  9. return bin(x).count('1')
  10. def ctz(x):
  11. return len(bin(x)) - len(bin(x).rstrip('0'))
  12. def dumptags(args, mdir, f):
  13. if args.all:
  14. tags = mdir.all_
  15. elif args.log:
  16. tags = mdir.log
  17. else:
  18. tags = mdir.tags
  19. for k, tag in enumerate(tags):
  20. f.write("tag %08x %s" % (tag, tag.typerepr()))
  21. if tag.id != 0x3ff:
  22. f.write(" id %d" % tag.id)
  23. if tag.size != 0x3ff:
  24. f.write(" size %d" % tag.size)
  25. if tag.is_('name'):
  26. f.write(" name %s" %
  27. json.dumps(tag.data.decode('utf8')))
  28. if tag.is_('dirstruct'):
  29. f.write(" dir {%#x, %#x}" % struct.unpack(
  30. '<II', tag.data[:8].ljust(8, b'\xff')))
  31. if tag.is_('ctzstruct'):
  32. f.write(" ctz {%#x} size %d" % struct.unpack(
  33. '<II', tag.data[:8].ljust(8, b'\xff')))
  34. if tag.is_('inlinestruct'):
  35. f.write(" inline size %d" % tag.size)
  36. if tag.is_('gstate'):
  37. f.write(" 0x%s" % ''.join('%02x' % c for c in tag.data))
  38. if tag.is_('tail'):
  39. f.write(" tail {%#x, %#x}" % struct.unpack(
  40. '<II', tag.data[:8].ljust(8, b'\xff')))
  41. f.write("\n")
  42. if args.data:
  43. for i in range(0, len(tag.data), 16):
  44. f.write(" %-47s %-16s\n" % (
  45. ' '.join('%02x' % c for c in tag.data[i:i+16]),
  46. ''.join(c if c >= ' ' and c <= '~' else '.'
  47. for c in map(chr, tag.data[i:i+16]))))
  48. def dumpentries(args, mdir, f):
  49. for k, id_ in enumerate(mdir.ids):
  50. name = mdir[Tag('name', id_, 0)]
  51. struct_ = mdir[Tag('struct', id_, 0)]
  52. f.write("id %d %s %s" % (
  53. id_, name.typerepr(),
  54. json.dumps(name.data.decode('utf8'))))
  55. if struct_.is_('dirstruct'):
  56. f.write(" dir {%#x, %#x}" % struct.unpack(
  57. '<II', struct_.data[:8].ljust(8, b'\xff')))
  58. if struct_.is_('ctzstruct'):
  59. f.write(" ctz {%#x} size %d" % struct.unpack(
  60. '<II', struct_.data[:8].ljust(8, b'\xff')))
  61. if struct_.is_('inlinestruct'):
  62. f.write(" inline size %d" % struct_.size)
  63. f.write("\n")
  64. if args.data and struct_.is_('inlinestruct'):
  65. for i in range(0, len(struct_.data), 16):
  66. f.write(" %-47s %-16s\n" % (
  67. ' '.join('%02x' % c for c in struct_.data[i:i+16]),
  68. ''.join(c if c >= ' ' and c <= '~' else '.'
  69. for c in map(chr, struct_.data[i:i+16]))))
  70. elif args.data and struct_.is_('ctzstruct'):
  71. block, size = struct.unpack(
  72. '<II', struct_.data[:8].ljust(8, b'\xff'))
  73. data = []
  74. i = 0 if size == 0 else (size-1) // (args.block_size - 8)
  75. if i != 0:
  76. i = ((size-1) - 4*popc(i-1)+2) // (args.block_size - 8)
  77. with open(args.disk, 'rb') as f2:
  78. while i >= 0:
  79. f2.seek(block * args.block_size)
  80. dat = f2.read(args.block_size)
  81. data.append(dat[4*(ctz(i)+1) if i != 0 else 0:])
  82. block, = struct.unpack('<I', dat[:4].ljust(4, b'\xff'))
  83. i -= 1
  84. data = bytes(it.islice(
  85. it.chain.from_iterable(reversed(data)), size))
  86. for i in range(0, min(len(data), 256)
  87. if not args.no_truncate else len(data), 16):
  88. f.write(" %-47s %-16s\n" % (
  89. ' '.join('%02x' % c for c in data[i:i+16]),
  90. ''.join(c if c >= ' ' and c <= '~' else '.'
  91. for c in map(chr, data[i:i+16]))))
  92. for tag in mdir.tags:
  93. if tag.id==id_ and tag.is_('userattr'):
  94. f.write("id %d %s size %d\n" % (
  95. id_, tag.typerepr(), tag.size))
  96. if args.data:
  97. for i in range(0, len(tag.data), 16):
  98. f.write(" %-47s %-16s\n" % (
  99. ' '.join('%02x' % c for c in tag.data[i:i+16]),
  100. ''.join(c if c >= ' ' and c <= '~' else '.'
  101. for c in map(chr, tag.data[i:i+16]))))
  102. def main(args):
  103. with open(args.disk, 'rb') as f:
  104. dirs = []
  105. superblock = None
  106. gstate = b''
  107. mdirs = []
  108. tail = (args.block1, args.block2)
  109. hard = False
  110. while True:
  111. # load mdir
  112. data = []
  113. blocks = {}
  114. for block in tail:
  115. f.seek(block * args.block_size)
  116. data.append(f.read(args.block_size)
  117. .ljust(args.block_size, b'\xff'))
  118. blocks[id(data[-1])] = block
  119. mdir = MetadataPair(data)
  120. mdir.blocks = tuple(blocks[id(p.data)] for p in mdir.pair)
  121. # fetch some key metadata as a we scan
  122. try:
  123. mdir.tail = mdir[Tag('tail', 0, 0)]
  124. if mdir.tail.size != 8 or mdir.tail.data == 8*b'\xff':
  125. mdir.tail = None
  126. except KeyError:
  127. mdir.tail = None
  128. # have superblock?
  129. try:
  130. nsuperblock = mdir[
  131. Tag(0x7ff, 0x3ff, 0), Tag('superblock', 0, 0)]
  132. superblock = nsuperblock, mdir[Tag('inlinestruct', 0, 0)]
  133. except KeyError:
  134. pass
  135. # have gstate?
  136. try:
  137. ngstate = mdir[Tag('movestate', 0, 0)]
  138. gstate = bytes((a or 0) ^ (b or 0)
  139. for a,b in it.zip_longest(gstate, ngstate.data))
  140. except KeyError:
  141. pass
  142. # add to directories
  143. mdirs.append(mdir)
  144. if mdir.tail is None or not mdir.tail.is_('hardtail'):
  145. dirs.append(mdirs)
  146. mdirs = []
  147. if mdir.tail is None:
  148. break
  149. tail = struct.unpack('<II', mdir.tail.data)
  150. hard = mdir.tail.is_('hardtail')
  151. # find paths
  152. dirtable = {}
  153. for dir in dirs:
  154. dirtable[tuple(sorted(dir[0].blocks))] = dir
  155. pending = [("/", dirs[0])]
  156. while pending:
  157. path, dir = pending.pop(0)
  158. for mdir in dir:
  159. for tag in mdir.tags:
  160. if tag.is_('dir'):
  161. try:
  162. npath = tag.data.decode('utf8')
  163. dirstruct = mdir[Tag('dirstruct', tag.id, 0)]
  164. nblocks = struct.unpack('<II', dirstruct.data)
  165. nmdir = dirtable[tuple(sorted(nblocks))]
  166. pending.append(((path + '/' + npath), nmdir))
  167. except KeyError:
  168. pass
  169. dir[0].path = path.replace('//', '/')
  170. # dump tree
  171. if not args.superblock and not args.gstate and not args.mdirs:
  172. args.superblock = True
  173. args.gstate = True
  174. args.mdirs = True
  175. if args.superblock and superblock:
  176. print("superblock %s v%d.%d" % (
  177. json.dumps(superblock[0].data.decode('utf8')),
  178. struct.unpack('<H', superblock[1].data[2:2+2])[0],
  179. struct.unpack('<H', superblock[1].data[0:0+2])[0]))
  180. print(
  181. " block_size %d\n"
  182. " block_count %d\n"
  183. " name_max %d\n"
  184. " file_max %d\n"
  185. " attr_max %d" % struct.unpack(
  186. '<IIIII', superblock[1].data[4:4+20].ljust(20, b'\xff')))
  187. if args.gstate and gstate:
  188. print("gstate 0x%s" % ''.join('%02x' % c for c in gstate))
  189. tag = Tag(struct.unpack('<I', gstate[0:4].ljust(4, b'\xff'))[0])
  190. blocks = struct.unpack('<II', gstate[4:4+8].ljust(8, b'\xff'))
  191. if tag.size:
  192. print(" orphans %d" % tag.size)
  193. if tag.type:
  194. print(" move dir {%#x, %#x} id %d" % (
  195. blocks[0], blocks[1], tag.id))
  196. if args.mdirs:
  197. for i, dir in enumerate(dirs):
  198. print("dir %s" % (json.dumps(dir[0].path)
  199. if hasattr(dir[0], 'path') else '(orphan)'))
  200. for j, mdir in enumerate(dir):
  201. print("mdir {%#x, %#x} rev %d%s" % (
  202. mdir.blocks[0], mdir.blocks[1], mdir.rev,
  203. ' (corrupted)' if not mdir else ''))
  204. f = io.StringIO()
  205. if args.tags or args.all or args.log:
  206. dumptags(args, mdir, f)
  207. else:
  208. dumpentries(args, mdir, f)
  209. lines = list(filter(None, f.getvalue().split('\n')))
  210. for k, line in enumerate(lines):
  211. print("%s %s" % (
  212. ' ' if j == len(dir)-1 else
  213. 'v' if k == len(lines)-1 else
  214. '|',
  215. line))
  216. return 0 if all(mdir for dir in dirs for mdir in dir) else 1
  217. if __name__ == "__main__":
  218. import argparse
  219. import sys
  220. parser = argparse.ArgumentParser(
  221. description="Dump semantic info about the metadata tree in littlefs")
  222. parser.add_argument('disk',
  223. help="File representing the block device.")
  224. parser.add_argument('block_size', type=lambda x: int(x, 0),
  225. help="Size of a block in bytes.")
  226. parser.add_argument('block1', nargs='?', default=0,
  227. type=lambda x: int(x, 0),
  228. help="Optional first block address for finding the root.")
  229. parser.add_argument('block2', nargs='?', default=1,
  230. type=lambda x: int(x, 0),
  231. help="Optional second block address for finding the root.")
  232. parser.add_argument('-s', '--superblock', action='store_true',
  233. help="Show contents of the superblock.")
  234. parser.add_argument('-g', '--gstate', action='store_true',
  235. help="Show contents of global-state.")
  236. parser.add_argument('-m', '--mdirs', action='store_true',
  237. help="Show contents of metadata-pairs/directories.")
  238. parser.add_argument('-t', '--tags', action='store_true',
  239. help="Show metadata tags instead of reconstructing entries.")
  240. parser.add_argument('-a', '--all', action='store_true',
  241. help="Show all tags in log, included tags in corrupted commits.")
  242. parser.add_argument('-l', '--log', action='store_true',
  243. help="Show tags in log.")
  244. parser.add_argument('-d', '--data', action='store_true',
  245. help="Also show the raw contents of files/attrs/tags.")
  246. parser.add_argument('-T', '--no-truncate', action='store_true',
  247. help="Don't truncate large amounts of data in files.")
  248. sys.exit(main(parser.parse_args()))