parttool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #!/usr/bin/env python
  2. #
  3. # parttool is used to perform partition level operations - reading,
  4. # writing, erasing and getting info about the partition.
  5. #
  6. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http:#www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. from __future__ import print_function, division
  20. import argparse
  21. import os
  22. import sys
  23. import subprocess
  24. import tempfile
  25. import re
  26. import gen_esp32part as gen
  27. __version__ = '2.0'
  28. COMPONENTS_PATH = os.path.expandvars(os.path.join("$IDF_PATH", "components"))
  29. ESPTOOL_PY = os.path.join(COMPONENTS_PATH, "esptool_py", "esptool", "esptool.py")
  30. PARTITION_TABLE_OFFSET = 0x8000
  31. quiet = False
  32. def status(msg):
  33. if not quiet:
  34. print(msg)
  35. class _PartitionId():
  36. def __init__(self, name=None, type=None, subtype=None):
  37. self.name = name
  38. self.type = type
  39. self.subtype = subtype
  40. class PartitionName(_PartitionId):
  41. def __init__(self, name):
  42. _PartitionId.__init__(self, name=name)
  43. class PartitionType(_PartitionId):
  44. def __init__(self, type, subtype):
  45. _PartitionId.__init__(self, type=type, subtype=subtype)
  46. PARTITION_BOOT_DEFAULT = _PartitionId()
  47. class ParttoolTarget():
  48. def __init__(self, port=None, baud=None, partition_table_offset=PARTITION_TABLE_OFFSET, partition_table_file=None,
  49. esptool_args=[], esptool_write_args=[], esptool_read_args=[], esptool_erase_args=[]):
  50. self.port = port
  51. self.baud = baud
  52. gen.offset_part_table = partition_table_offset
  53. def parse_esptool_args(esptool_args):
  54. results = list()
  55. for arg in esptool_args:
  56. pattern = re.compile(r"(.+)=(.+)")
  57. result = pattern.match(arg)
  58. try:
  59. key = result.group(1)
  60. value = result.group(2)
  61. results.extend(["--" + key, value])
  62. except AttributeError:
  63. results.extend(["--" + arg])
  64. return results
  65. self.esptool_args = parse_esptool_args(esptool_args)
  66. self.esptool_write_args = parse_esptool_args(esptool_write_args)
  67. self.esptool_read_args = parse_esptool_args(esptool_read_args)
  68. self.esptool_erase_args = parse_esptool_args(esptool_erase_args)
  69. if partition_table_file:
  70. partition_table = None
  71. with open(partition_table_file, "rb") as f:
  72. input_is_binary = (f.read(2) == gen.PartitionDefinition.MAGIC_BYTES)
  73. f.seek(0)
  74. if input_is_binary:
  75. partition_table = gen.PartitionTable.from_binary(f.read())
  76. if partition_table is None:
  77. with open(partition_table_file, "r") as f:
  78. f.seek(0)
  79. partition_table = gen.PartitionTable.from_csv(f.read())
  80. else:
  81. temp_file = tempfile.NamedTemporaryFile(delete=False)
  82. temp_file.close()
  83. try:
  84. self._call_esptool(["read_flash", str(partition_table_offset), str(gen.MAX_PARTITION_LENGTH), temp_file.name])
  85. with open(temp_file.name, "rb") as f:
  86. partition_table = gen.PartitionTable.from_binary(f.read())
  87. finally:
  88. os.unlink(temp_file.name)
  89. self.partition_table = partition_table
  90. def _call_esptool(self, args, out=None):
  91. esptool_args = [sys.executable, ESPTOOL_PY] + self.esptool_args
  92. if self.port:
  93. esptool_args += ["--port", self.port]
  94. if self.baud:
  95. esptool_args += ["--baud", str(self.baud)]
  96. esptool_args += args
  97. with open(os.devnull, "w") as null_file:
  98. subprocess.check_call(esptool_args, stdout=null_file, stderr=null_file)
  99. def get_partition_info(self, partition_id):
  100. partition = None
  101. if partition_id.name:
  102. partition = self.partition_table.find_by_name(partition_id.name)
  103. elif partition_id.type and partition_id.subtype:
  104. partition = self.partition_table.find_by_type(partition_id.type, partition_id.subtype)
  105. else: # default boot partition
  106. search = ["factory"] + ["ota_{}".format(d) for d in range(16)]
  107. for subtype in search:
  108. partition = self.partition_table.find_by_type("app", subtype)
  109. if partition:
  110. break
  111. if not partition:
  112. raise Exception("Partition does not exist")
  113. return partition
  114. def erase_partition(self, partition_id):
  115. partition = self.get_partition_info(partition_id)
  116. self._call_esptool(["erase_region", str(partition.offset), str(partition.size)] + self.esptool_erase_args)
  117. def read_partition(self, partition_id, output):
  118. partition = self.get_partition_info(partition_id)
  119. self._call_esptool(["read_flash", str(partition.offset), str(partition.size), output] + self.esptool_read_args)
  120. def write_partition(self, partition_id, input):
  121. self.erase_partition(partition_id)
  122. partition = self.get_partition_info(partition_id)
  123. with open(input, "rb") as input_file:
  124. content_len = len(input_file.read())
  125. if content_len > partition.size:
  126. raise Exception("Input file size exceeds partition size")
  127. self._call_esptool(["write_flash", str(partition.offset), input] + self.esptool_write_args)
  128. def _write_partition(target, partition_id, input):
  129. target.write_partition(partition_id, input)
  130. partition = target.get_partition_info(partition_id)
  131. status("Written contents of file '{}' at offset 0x{:x}".format(input, partition.offset))
  132. def _read_partition(target, partition_id, output):
  133. target.read_partition(partition_id, output)
  134. partition = target.get_partition_info(partition_id)
  135. status("Read partition '{}' contents from device at offset 0x{:x} to file '{}'"
  136. .format(partition.name, partition.offset, output))
  137. def _erase_partition(target, partition_id):
  138. target.erase_partition(partition_id)
  139. partition = target.get_partition_info(partition_id)
  140. status("Erased partition '{}' at offset 0x{:x}".format(partition.name, partition.offset))
  141. def _get_partition_info(target, partition_id, info):
  142. try:
  143. partition = target.get_partition_info(partition_id)
  144. except Exception:
  145. return
  146. info_dict = {
  147. "offset": '0x{:x}'.format(partition.offset),
  148. "size": '0x{:x}'.format(partition.size)
  149. }
  150. infos = []
  151. try:
  152. for i in info:
  153. infos += [info_dict[i]]
  154. except KeyError:
  155. raise RuntimeError("Request for unknown partition info {}".format(i))
  156. print(" ".join(infos))
  157. def main():
  158. global quiet
  159. parser = argparse.ArgumentParser("ESP-IDF Partitions Tool")
  160. parser.add_argument("--quiet", "-q", help="suppress stderr messages", action="store_true")
  161. parser.add_argument("--esptool-args", help="additional main arguments for esptool", nargs="+")
  162. parser.add_argument("--esptool-write-args", help="additional subcommand arguments when writing to flash", nargs="+")
  163. parser.add_argument("--esptool-read-args", help="additional subcommand arguments when reading flash", nargs="+")
  164. parser.add_argument("--esptool-erase-args", help="additional subcommand arguments when erasing regions of flash", nargs="+")
  165. # By default the device attached to the specified port is queried for the partition table. If a partition table file
  166. # is specified, that is used instead.
  167. parser.add_argument("--port", "-p", help="port where the target device of the command is connected to; the partition table is sourced from this device \
  168. when the partition table file is not defined")
  169. parser.add_argument("--baud", "-b", help="baudrate to use", type=int)
  170. parser.add_argument("--partition-table-offset", "-o", help="offset to read the partition table from", type=str)
  171. parser.add_argument("--partition-table-file", "-f", help="file (CSV/binary) to read the partition table from; \
  172. overrides device attached to specified port as the partition table source when defined")
  173. partition_selection_parser = argparse.ArgumentParser(add_help=False)
  174. # Specify what partition to perform the operation on. This can either be specified using the
  175. # partition name or the first partition that matches the specified type/subtype
  176. partition_selection_args = partition_selection_parser.add_mutually_exclusive_group()
  177. partition_selection_args.add_argument("--partition-name", "-n", help="name of the partition")
  178. partition_selection_args.add_argument("--partition-type", "-t", help="type of the partition")
  179. partition_selection_args.add_argument('--partition-boot-default', "-d", help='select the default boot partition \
  180. using the same fallback logic as the IDF bootloader', action="store_true")
  181. partition_selection_parser.add_argument("--partition-subtype", "-s", help="subtype of the partition")
  182. subparsers = parser.add_subparsers(dest="operation", help="run parttool -h for additional help")
  183. # Specify the supported operations
  184. read_part_subparser = subparsers.add_parser("read_partition", help="read partition from device and dump contents into a file",
  185. parents=[partition_selection_parser])
  186. read_part_subparser.add_argument("--output", help="file to dump the read partition contents to")
  187. write_part_subparser = subparsers.add_parser("write_partition", help="write contents of a binary file to partition on device",
  188. parents=[partition_selection_parser])
  189. write_part_subparser.add_argument("--input", help="file whose contents are to be written to the partition offset")
  190. subparsers.add_parser("erase_partition", help="erase the contents of a partition on the device", parents=[partition_selection_parser])
  191. print_partition_info_subparser = subparsers.add_parser("get_partition_info", help="get partition information", parents=[partition_selection_parser])
  192. print_partition_info_subparser.add_argument("--info", help="type of partition information to get",
  193. choices=["offset", "size"], default=["offset", "size"], nargs="+")
  194. args = parser.parse_args()
  195. quiet = args.quiet
  196. # No operation specified, display help and exit
  197. if args.operation is None:
  198. if not quiet:
  199. parser.print_help()
  200. sys.exit(1)
  201. # Prepare the partition to perform operation on
  202. if args.partition_name:
  203. partition_id = PartitionName(args.partition_name)
  204. elif args.partition_type:
  205. if not args.partition_subtype:
  206. raise RuntimeError("--partition-subtype should be defined when --partition-type is defined")
  207. partition_id = PartitionType(args.partition_type, args.partition_subtype)
  208. elif args.partition_boot_default:
  209. partition_id = PARTITION_BOOT_DEFAULT
  210. else:
  211. raise RuntimeError("Partition to operate on should be defined using --partition-name OR \
  212. partition-type,--partition-subtype OR partition-boot-default")
  213. # Prepare the device to perform operation on
  214. target_args = {}
  215. if args.port:
  216. target_args["port"] = args.port
  217. if args.baud:
  218. target_args["baud"] = args.baud
  219. if args.partition_table_file:
  220. target_args["partition_table_file"] = args.partition_table_file
  221. if args.partition_table_offset:
  222. target_args["partition_table_offset"] = int(args.partition_table_offset, 0)
  223. if args.esptool_args:
  224. target_args["esptool_args"] = args.esptool_args
  225. if args.esptool_write_args:
  226. target_args["esptool_write_args"] = args.esptool_write_args
  227. if args.esptool_read_args:
  228. target_args["esptool_read_args"] = args.esptool_read_args
  229. if args.esptool_erase_args:
  230. target_args["esptool_erase_args"] = args.esptool_erase_args
  231. target = ParttoolTarget(**target_args)
  232. # Create the operation table and execute the operation
  233. common_args = {'target':target, 'partition_id':partition_id}
  234. parttool_ops = {
  235. 'erase_partition':(_erase_partition, []),
  236. 'read_partition':(_read_partition, ["output"]),
  237. 'write_partition':(_write_partition, ["input"]),
  238. 'get_partition_info':(_get_partition_info, ["info"])
  239. }
  240. (op, op_args) = parttool_ops[args.operation]
  241. for op_arg in op_args:
  242. common_args.update({op_arg:vars(args)[op_arg]})
  243. if quiet:
  244. # If exceptions occur, suppress and exit quietly
  245. try:
  246. op(**common_args)
  247. except Exception:
  248. sys.exit(2)
  249. else:
  250. try:
  251. op(**common_args)
  252. except gen.InputError as e:
  253. print(e, file=sys.stderr)
  254. sys.exit(2)
  255. if __name__ == '__main__':
  256. main()