readmdir.py 10 KB

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