readmdir.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. try:
  84. if ' ' in type:
  85. type1, type3 = type.split()
  86. return (self.is_(type1) and
  87. (self.type & ~TAG_TYPES[type1][0]) == int(type3, 0))
  88. return self.type == int(type, 0)
  89. except (ValueError, KeyError):
  90. return (self.type & TAG_TYPES[type][0]) == TAG_TYPES[type][1]
  91. def mkmask(self):
  92. return Tag(
  93. 0x700 if self.isunique else 0x7ff,
  94. 0x3ff if self.isattr else 0,
  95. 0)
  96. def chid(self, nid):
  97. ntag = Tag(self.type, nid, self.size)
  98. if hasattr(self, 'off'): ntag.off = self.off
  99. if hasattr(self, 'data'): ntag.data = self.data
  100. if hasattr(self, 'crc'): ntag.crc = self.crc
  101. if hasattr(self, 'erased'): ntag.erased = self.erased
  102. return ntag
  103. def typerepr(self):
  104. if self.is_('crc') and getattr(self, 'crc', 0xffffffff) != 0xffffffff:
  105. crc_status = ' (bad)'
  106. elif self.is_('crc') and getattr(self, 'erased', False):
  107. crc_status = ' (era)'
  108. else:
  109. crc_status = ''
  110. reverse_types = {v: k for k, v in TAG_TYPES.items()}
  111. for prefix in range(12):
  112. mask = 0x7ff & ~((1 << prefix)-1)
  113. if (mask, self.type & mask) in reverse_types:
  114. type = reverse_types[mask, self.type & mask]
  115. if prefix > 0:
  116. return '%s %#x%s' % (
  117. type, self.type & ((1 << prefix)-1), crc_status)
  118. else:
  119. return '%s%s' % (type, crc_status)
  120. else:
  121. return '%02x%s' % (self.type, crc_status)
  122. def idrepr(self):
  123. return repr(self.id) if self.id != 0x3ff else '.'
  124. def sizerepr(self):
  125. return repr(self.size) if self.size != 0x3ff else 'x'
  126. def __repr__(self):
  127. return 'Tag(%r, %d, %d)' % (self.typerepr(), self.id, self.size)
  128. def __lt__(self, other):
  129. return (self.id, self.type) < (other.id, other.type)
  130. def __bool__(self):
  131. return self.isvalid
  132. def __int__(self):
  133. return self.tag
  134. def __index__(self):
  135. return self.tag
  136. class MetadataPair:
  137. def __init__(self, blocks):
  138. if len(blocks) > 1:
  139. self.pair = [MetadataPair([block]) for block in blocks]
  140. self.pair = sorted(self.pair, reverse=True)
  141. self.data = self.pair[0].data
  142. self.rev = self.pair[0].rev
  143. self.tags = self.pair[0].tags
  144. self.ids = self.pair[0].ids
  145. self.log = self.pair[0].log
  146. self.all_ = self.pair[0].all_
  147. return
  148. self.pair = [self]
  149. self.data = blocks[0]
  150. block = self.data
  151. self.rev, = struct.unpack('<I', block[0:4])
  152. crc = binascii.crc32(block[0:4])
  153. # parse tags
  154. corrupt = False
  155. tag = Tag(0xffffffff)
  156. off = 4
  157. self.log = []
  158. self.all_ = []
  159. while len(block) - off >= 4:
  160. ntag, = struct.unpack('>I', block[off:off+4])
  161. tag = Tag((int(tag) ^ ntag) & 0x7fffffff)
  162. tag.off = off + 4
  163. tag.data = block[off+4:off+tag.dsize]
  164. if tag.is_('crc 0x3'):
  165. crc = binascii.crc32(block[off:off+4*4], crc)
  166. elif tag.is_('crc'):
  167. crc = binascii.crc32(block[off:off+2*4], crc)
  168. else:
  169. crc = binascii.crc32(block[off:off+tag.dsize], crc)
  170. tag.crc = crc
  171. off += tag.dsize
  172. self.all_.append(tag)
  173. if tag.is_('crc'):
  174. # is valid commit?
  175. if crc != 0xffffffff:
  176. corrupt = True
  177. if not corrupt:
  178. self.log = self.all_.copy()
  179. # end of commit?
  180. if tag.is_('crc 0x3'):
  181. esize, ecrc = struct.unpack('<II', tag.data[:8])
  182. dcrc = 0xffffffff ^ binascii.crc32(block[off:off+esize])
  183. if ecrc == dcrc:
  184. tag.erased = True
  185. corrupt = True
  186. elif tag.is_('crc 0x2'):
  187. corrupt = True
  188. # reset tag parsing
  189. crc = 0
  190. # find active ids
  191. self.ids = list(it.takewhile(
  192. lambda id: Tag('name', id, 0) in self,
  193. it.count()))
  194. # find most recent tags
  195. self.tags = []
  196. for tag in self.log:
  197. if tag.is_('crc') or tag.is_('splice'):
  198. continue
  199. elif tag.id == 0x3ff:
  200. if tag in self and self[tag] is tag:
  201. self.tags.append(tag)
  202. else:
  203. # id could have change, I know this is messy and slow
  204. # but it works
  205. for id in self.ids:
  206. ntag = tag.chid(id)
  207. if ntag in self and self[ntag] is tag:
  208. self.tags.append(ntag)
  209. self.tags = sorted(self.tags)
  210. def __bool__(self):
  211. return bool(self.log)
  212. def __lt__(self, other):
  213. # corrupt blocks don't count
  214. if not self or not other:
  215. return bool(other)
  216. # use sequence arithmetic to avoid overflow
  217. return not ((other.rev - self.rev) & 0x80000000)
  218. def __contains__(self, args):
  219. try:
  220. self[args]
  221. return True
  222. except KeyError:
  223. return False
  224. def __getitem__(self, args):
  225. if isinstance(args, tuple):
  226. gmask, gtag = args
  227. else:
  228. gmask, gtag = args.mkmask(), args
  229. gdiff = 0
  230. for tag in reversed(self.log):
  231. if (gmask.id != 0 and tag.is_('splice') and
  232. tag.id <= gtag.id - gdiff):
  233. if tag.is_('create') and tag.id == gtag.id - gdiff:
  234. # creation point
  235. break
  236. gdiff += tag.schunk
  237. if ((int(gmask) & int(tag)) ==
  238. (int(gmask) & int(gtag.chid(gtag.id - gdiff)))):
  239. if tag.size == 0x3ff:
  240. # deleted
  241. break
  242. return tag
  243. raise KeyError(gmask, gtag)
  244. def _dump_tags(self, tags, f=sys.stdout, truncate=True):
  245. f.write("%-8s %-8s %-13s %4s %4s" % (
  246. 'off', 'tag', 'type', 'id', 'len'))
  247. if truncate:
  248. f.write(' data (truncated)')
  249. f.write('\n')
  250. for tag in tags:
  251. f.write("%08x: %08x %-13s %4s %4s" % (
  252. tag.off, tag,
  253. tag.typerepr(), tag.idrepr(), tag.sizerepr()))
  254. if truncate:
  255. f.write(" %-23s %-8s\n" % (
  256. ' '.join('%02x' % c for c in tag.data[:8]),
  257. ''.join(c if c >= ' ' and c <= '~' else '.'
  258. for c in map(chr, tag.data[:8]))))
  259. else:
  260. f.write("\n")
  261. for i in range(0, len(tag.data), 16):
  262. f.write(" %08x: %-47s %-16s\n" % (
  263. tag.off+i,
  264. ' '.join('%02x' % c for c in tag.data[i:i+16]),
  265. ''.join(c if c >= ' ' and c <= '~' else '.'
  266. for c in map(chr, tag.data[i:i+16]))))
  267. def dump_tags(self, f=sys.stdout, truncate=True):
  268. self._dump_tags(self.tags, f=f, truncate=truncate)
  269. def dump_log(self, f=sys.stdout, truncate=True):
  270. self._dump_tags(self.log, f=f, truncate=truncate)
  271. def dump_all(self, f=sys.stdout, truncate=True):
  272. self._dump_tags(self.all_, f=f, truncate=truncate)
  273. def main(args):
  274. blocks = []
  275. with open(args.disk, 'rb') as f:
  276. for block in [args.block1, args.block2]:
  277. if block is None:
  278. continue
  279. f.seek(block * args.block_size)
  280. blocks.append(f.read(args.block_size)
  281. .ljust(args.block_size, b'\xff'))
  282. # find most recent pair
  283. mdir = MetadataPair(blocks)
  284. try:
  285. mdir.tail = mdir[Tag('tail', 0, 0)]
  286. if mdir.tail.size != 8 or mdir.tail.data == 8*b'\xff':
  287. mdir.tail = None
  288. except KeyError:
  289. mdir.tail = None
  290. print("mdir {%s} rev %d%s%s%s" % (
  291. ', '.join('%#x' % b
  292. for b in [args.block1, args.block2]
  293. if b is not None),
  294. mdir.rev,
  295. ' (was %s)' % ', '.join('%d' % m.rev for m in mdir.pair[1:])
  296. if len(mdir.pair) > 1 else '',
  297. ' (corrupted!)' if not mdir else '',
  298. ' -> {%#x, %#x}' % struct.unpack('<II', mdir.tail.data)
  299. if mdir.tail else ''))
  300. if args.all:
  301. mdir.dump_all(truncate=not args.no_truncate)
  302. elif args.log:
  303. mdir.dump_log(truncate=not args.no_truncate)
  304. else:
  305. mdir.dump_tags(truncate=not args.no_truncate)
  306. return 0 if mdir else 1
  307. if __name__ == "__main__":
  308. import argparse
  309. import sys
  310. parser = argparse.ArgumentParser(
  311. description="Dump useful info about metadata pairs in littlefs.")
  312. parser.add_argument('disk',
  313. help="File representing the block device.")
  314. parser.add_argument('block_size', type=lambda x: int(x, 0),
  315. help="Size of a block in bytes.")
  316. parser.add_argument('block1', type=lambda x: int(x, 0),
  317. help="First block address for finding the metadata pair.")
  318. parser.add_argument('block2', nargs='?', type=lambda x: int(x, 0),
  319. help="Second block address for finding the metadata pair.")
  320. parser.add_argument('-l', '--log', action='store_true',
  321. help="Show tags in log.")
  322. parser.add_argument('-a', '--all', action='store_true',
  323. help="Show all tags in log, included tags in corrupted commits.")
  324. parser.add_argument('-T', '--no-truncate', action='store_true',
  325. help="Don't truncate large amounts of data.")
  326. sys.exit(main(parser.parse_args()))