readmdir.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env python3
  2. import struct
  3. import binascii
  4. import sys
  5. import itertools as it
  6. TAG_TYPES = {
  7. 'splice': (0x700, 0x400),
  8. 'create': (0x7ff, 0x401),
  9. 'delete': (0x7ff, 0x4ff),
  10. 'name': (0x700, 0x000),
  11. 'reg': (0x7ff, 0x001),
  12. 'dir': (0x7ff, 0x002),
  13. 'superblock': (0x7ff, 0x0ff),
  14. 'struct': (0x700, 0x200),
  15. 'dirstruct': (0x7ff, 0x200),
  16. 'ctzstruct': (0x7ff, 0x202),
  17. 'inlinestruct': (0x7ff, 0x201),
  18. 'userattr': (0x700, 0x300),
  19. 'tail': (0x700, 0x600),
  20. 'softtail': (0x7ff, 0x600),
  21. 'hardtail': (0x7ff, 0x601),
  22. 'gstate': (0x700, 0x700),
  23. 'movestate': (0x7ff, 0x7ff),
  24. 'crc': (0x700, 0x500),
  25. }
  26. class Tag:
  27. def __init__(self, *args):
  28. if len(args) == 1:
  29. self.tag = args[0]
  30. elif len(args) == 3:
  31. if isinstance(args[0], str):
  32. type = TAG_TYPES[args[0]][1]
  33. else:
  34. type = args[0]
  35. if isinstance(args[1], str):
  36. id = int(args[1], 0) if args[1] not in 'x.' else 0x3ff
  37. else:
  38. id = args[1]
  39. if isinstance(args[2], str):
  40. size = int(args[2], str) if args[2] not in 'x.' else 0x3ff
  41. else:
  42. size = args[2]
  43. self.tag = (type << 20) | (id << 10) | size
  44. else:
  45. assert False
  46. @property
  47. def isvalid(self):
  48. return not bool(self.tag & 0x80000000)
  49. @property
  50. def isattr(self):
  51. return not bool(self.tag & 0x40000000)
  52. @property
  53. def iscompactable(self):
  54. return bool(self.tag & 0x20000000)
  55. @property
  56. def isunique(self):
  57. return not bool(self.tag & 0x10000000)
  58. @property
  59. def type(self):
  60. return (self.tag & 0x7ff00000) >> 20
  61. @property
  62. def type1(self):
  63. return (self.tag & 0x70000000) >> 20
  64. @property
  65. def type3(self):
  66. return (self.tag & 0x7ff00000) >> 20
  67. @property
  68. def id(self):
  69. return (self.tag & 0x000ffc00) >> 10
  70. @property
  71. def size(self):
  72. return (self.tag & 0x000003ff) >> 0
  73. @property
  74. def dsize(self):
  75. return 4 + (self.size if self.size != 0x3ff else 0)
  76. @property
  77. def chunk(self):
  78. return self.type & 0xff
  79. @property
  80. def schunk(self):
  81. return struct.unpack('b', struct.pack('B', self.chunk))[0]
  82. def is_(self, type):
  83. return (self.type & TAG_TYPES[type][0]) == TAG_TYPES[type][1]
  84. def mkmask(self):
  85. return Tag(
  86. 0x700 if self.isunique else 0x7ff,
  87. 0x3ff if self.isattr else 0,
  88. 0)
  89. def chid(self, nid):
  90. ntag = Tag(self.type, nid, self.size)
  91. if hasattr(self, 'off'): ntag.off = self.off
  92. if hasattr(self, 'data'): ntag.data = self.data
  93. if hasattr(self, 'crc'): ntag.crc = self.crc
  94. return ntag
  95. def typerepr(self):
  96. if self.is_('crc') and getattr(self, 'crc', 0xffffffff) != 0xffffffff:
  97. return 'crc (bad)'
  98. reverse_types = {v: k for k, v in TAG_TYPES.items()}
  99. for prefix in range(12):
  100. mask = 0x7ff & ~((1 << prefix)-1)
  101. if (mask, self.type & mask) in reverse_types:
  102. type = reverse_types[mask, self.type & mask]
  103. if prefix > 0:
  104. return '%s %#0*x' % (
  105. type, prefix//4, self.type & ((1 << prefix)-1))
  106. else:
  107. return type
  108. else:
  109. return '%02x' % self.type
  110. def idrepr(self):
  111. return repr(self.id) if self.id != 0x3ff else '.'
  112. def sizerepr(self):
  113. return repr(self.size) if self.size != 0x3ff else 'x'
  114. def __repr__(self):
  115. return 'Tag(%r, %d, %d)' % (self.typerepr(), self.id, self.size)
  116. def __lt__(self, other):
  117. return (self.id, self.type) < (other.id, other.type)
  118. def __bool__(self):
  119. return self.isvalid
  120. def __int__(self):
  121. return self.tag
  122. def __index__(self):
  123. return self.tag
  124. class MetadataPair:
  125. def __init__(self, blocks):
  126. if len(blocks) > 1:
  127. self.pair = [MetadataPair([block]) for block in blocks]
  128. self.pair = sorted(self.pair, reverse=True)
  129. self.data = self.pair[0].data
  130. self.rev = self.pair[0].rev
  131. self.tags = self.pair[0].tags
  132. self.ids = self.pair[0].ids
  133. self.log = self.pair[0].log
  134. self.all_ = self.pair[0].all_
  135. return
  136. self.pair = [self]
  137. self.data = blocks[0]
  138. block = self.data
  139. self.rev, = struct.unpack('<I', block[0:4])
  140. crc = binascii.crc32(block[0:4])
  141. # parse tags
  142. corrupt = False
  143. tag = Tag(0xffffffff)
  144. off = 4
  145. self.log = []
  146. self.all_ = []
  147. while len(block) - off >= 4:
  148. ntag, = struct.unpack('>I', block[off:off+4])
  149. tag = Tag(int(tag) ^ ntag)
  150. tag.off = off + 4
  151. tag.data = block[off+4:off+tag.dsize]
  152. if tag.is_('crc'):
  153. crc = binascii.crc32(block[off:off+4+4], crc)
  154. else:
  155. crc = binascii.crc32(block[off:off+tag.dsize], crc)
  156. tag.crc = crc
  157. off += tag.dsize
  158. self.all_.append(tag)
  159. if tag.is_('crc'):
  160. # is valid commit?
  161. if crc != 0xffffffff:
  162. corrupt = True
  163. if not corrupt:
  164. self.log = self.all_.copy()
  165. # reset tag parsing
  166. crc = 0
  167. tag = Tag(int(tag) ^ ((tag.type & 1) << 31))
  168. # find active ids
  169. self.ids = list(it.takewhile(
  170. lambda id: Tag('name', id, 0) in self,
  171. it.count()))
  172. # find most recent tags
  173. self.tags = []
  174. for tag in self.log:
  175. if tag.is_('crc') or tag.is_('splice'):
  176. continue
  177. elif tag.id == 0x3ff:
  178. if tag in self and self[tag] is tag:
  179. self.tags.append(tag)
  180. else:
  181. # id could have change, I know this is messy and slow
  182. # but it works
  183. for id in self.ids:
  184. ntag = tag.chid(id)
  185. if ntag in self and self[ntag] is tag:
  186. self.tags.append(ntag)
  187. self.tags = sorted(self.tags)
  188. def __bool__(self):
  189. return bool(self.log)
  190. def __lt__(self, other):
  191. # corrupt blocks don't count
  192. if not self or not other:
  193. return bool(other)
  194. # use sequence arithmetic to avoid overflow
  195. return not ((other.rev - self.rev) & 0x80000000)
  196. def __contains__(self, args):
  197. try:
  198. self[args]
  199. return True
  200. except KeyError:
  201. return False
  202. def __getitem__(self, args):
  203. if isinstance(args, tuple):
  204. gmask, gtag = args
  205. else:
  206. gmask, gtag = args.mkmask(), args
  207. gdiff = 0
  208. for tag in reversed(self.log):
  209. if (gmask.id != 0 and tag.is_('splice') and
  210. tag.id <= gtag.id - gdiff):
  211. if tag.is_('create') and tag.id == gtag.id - gdiff:
  212. # creation point
  213. break
  214. gdiff += tag.schunk
  215. if ((int(gmask) & int(tag)) ==
  216. (int(gmask) & int(gtag.chid(gtag.id - gdiff)))):
  217. if tag.size == 0x3ff:
  218. # deleted
  219. break
  220. return tag
  221. raise KeyError(gmask, gtag)
  222. def _dump_tags(self, tags, f=sys.stdout, truncate=True):
  223. f.write("%-8s %-8s %-13s %4s %4s" % (
  224. 'off', 'tag', 'type', 'id', 'len'))
  225. if truncate:
  226. f.write(' data (truncated)')
  227. f.write('\n')
  228. for tag in tags:
  229. f.write("%08x: %08x %-13s %4s %4s" % (
  230. tag.off, tag,
  231. tag.typerepr(), tag.idrepr(), tag.sizerepr()))
  232. if truncate:
  233. f.write(" %-23s %-8s\n" % (
  234. ' '.join('%02x' % c for c in tag.data[:8]),
  235. ''.join(c if c >= ' ' and c <= '~' else '.'
  236. for c in map(chr, tag.data[:8]))))
  237. else:
  238. f.write("\n")
  239. for i in range(0, len(tag.data), 16):
  240. f.write(" %08x: %-47s %-16s\n" % (
  241. tag.off+i,
  242. ' '.join('%02x' % c for c in tag.data[i:i+16]),
  243. ''.join(c if c >= ' ' and c <= '~' else '.'
  244. for c in map(chr, tag.data[i:i+16]))))
  245. def dump_tags(self, f=sys.stdout, truncate=True):
  246. self._dump_tags(self.tags, f=f, truncate=truncate)
  247. def dump_log(self, f=sys.stdout, truncate=True):
  248. self._dump_tags(self.log, f=f, truncate=truncate)
  249. def dump_all(self, f=sys.stdout, truncate=True):
  250. self._dump_tags(self.all_, f=f, truncate=truncate)
  251. def main(args):
  252. blocks = []
  253. with open(args.disk, 'rb') as f:
  254. for block in [args.block1, args.block2]:
  255. if block is None:
  256. continue
  257. f.seek(block * args.block_size)
  258. blocks.append(f.read(args.block_size)
  259. .ljust(args.block_size, b'\xff'))
  260. # find most recent pair
  261. mdir = MetadataPair(blocks)
  262. try:
  263. mdir.tail = mdir[Tag('tail', 0, 0)]
  264. if mdir.tail.size != 8 or mdir.tail.data == 8*b'\xff':
  265. mdir.tail = None
  266. except KeyError:
  267. mdir.tail = None
  268. print("mdir {%s} rev %d%s%s%s" % (
  269. ', '.join('%#x' % b
  270. for b in [args.block1, args.block2]
  271. if b is not None),
  272. mdir.rev,
  273. ' (was %s)' % ', '.join('%d' % m.rev for m in mdir.pair[1:])
  274. if len(mdir.pair) > 1 else '',
  275. ' (corrupted!)' if not mdir else '',
  276. ' -> {%#x, %#x}' % struct.unpack('<II', mdir.tail.data)
  277. if mdir.tail else ''))
  278. if args.all:
  279. mdir.dump_all(truncate=not args.no_truncate)
  280. elif args.log:
  281. mdir.dump_log(truncate=not args.no_truncate)
  282. else:
  283. mdir.dump_tags(truncate=not args.no_truncate)
  284. return 0 if mdir else 1
  285. if __name__ == "__main__":
  286. import argparse
  287. import sys
  288. parser = argparse.ArgumentParser(
  289. description="Dump useful info about metadata pairs in littlefs.")
  290. parser.add_argument('disk',
  291. help="File representing the block device.")
  292. parser.add_argument('block_size', type=lambda x: int(x, 0),
  293. help="Size of a block in bytes.")
  294. parser.add_argument('block1', type=lambda x: int(x, 0),
  295. help="First block address for finding the metadata pair.")
  296. parser.add_argument('block2', nargs='?', type=lambda x: int(x, 0),
  297. help="Second block address for finding the metadata pair.")
  298. parser.add_argument('-l', '--log', action='store_true',
  299. help="Show tags in log.")
  300. parser.add_argument('-a', '--all', action='store_true',
  301. help="Show all tags in log, included tags in corrupted commits.")
  302. parser.add_argument('-T', '--no-truncate', action='store_true',
  303. help="Don't truncate large amounts of data.")
  304. sys.exit(main(parser.parse_args()))