readmdir.py 12 KB

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