readmdir.py 12 KB

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