parttool.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. # set `out` to None to redirect the output to the STDOUT
  91. # otherwise set `out` to file descriptor
  92. # beware that the method does not close the file descriptor
  93. def _call_esptool(self, args, out=None):
  94. esptool_args = [sys.executable, ESPTOOL_PY] + self.esptool_args
  95. if self.port:
  96. esptool_args += ["--port", self.port]
  97. if self.baud:
  98. esptool_args += ["--baud", str(self.baud)]
  99. esptool_args += args
  100. print("Running %s..." % (" ".join(esptool_args)))
  101. try:
  102. subprocess.check_call(esptool_args, stdout=out, stderr=subprocess.STDOUT)
  103. except subprocess.CalledProcessError as e:
  104. print("An exception: **", str(e), "** occurred in _call_esptool.", file=out)
  105. raise e
  106. def get_partition_info(self, partition_id):
  107. partition = None
  108. if partition_id.name:
  109. partition = self.partition_table.find_by_name(partition_id.name)
  110. elif partition_id.type and partition_id.subtype:
  111. partition = self.partition_table.find_by_type(partition_id.type, partition_id.subtype)
  112. else: # default boot partition
  113. search = ["factory"] + ["ota_{}".format(d) for d in range(16)]
  114. for subtype in search:
  115. partition = self.partition_table.find_by_type("app", subtype)
  116. if partition:
  117. break
  118. if not partition:
  119. raise Exception("Partition does not exist")
  120. return partition
  121. def erase_partition(self, partition_id):
  122. partition = self.get_partition_info(partition_id)
  123. self._call_esptool(["erase_region", str(partition.offset), str(partition.size)] + self.esptool_erase_args)
  124. def read_partition(self, partition_id, output):
  125. partition = self.get_partition_info(partition_id)
  126. self._call_esptool(["read_flash", str(partition.offset), str(partition.size), output] + self.esptool_read_args)
  127. def write_partition(self, partition_id, input):
  128. self.erase_partition(partition_id)
  129. partition = self.get_partition_info(partition_id)
  130. with open(input, "rb") as input_file:
  131. content_len = len(input_file.read())
  132. if content_len > partition.size:
  133. raise Exception("Input file size exceeds partition size")
  134. self._call_esptool(["write_flash", str(partition.offset), input] + self.esptool_write_args)
  135. def _write_partition(target, partition_id, input):
  136. target.write_partition(partition_id, input)
  137. partition = target.get_partition_info(partition_id)
  138. status("Written contents of file '{}' at offset 0x{:x}".format(input, partition.offset))
  139. def _read_partition(target, partition_id, output):
  140. target.read_partition(partition_id, output)
  141. partition = target.get_partition_info(partition_id)
  142. status("Read partition '{}' contents from device at offset 0x{:x} to file '{}'"
  143. .format(partition.name, partition.offset, output))
  144. def _erase_partition(target, partition_id):
  145. target.erase_partition(partition_id)
  146. partition = target.get_partition_info(partition_id)
  147. status("Erased partition '{}' at offset 0x{:x}".format(partition.name, partition.offset))
  148. def _get_partition_info(target, partition_id, info):
  149. try:
  150. partition = target.get_partition_info(partition_id)
  151. except Exception:
  152. return
  153. info_dict = {
  154. "offset": '0x{:x}'.format(partition.offset),
  155. "size": '0x{:x}'.format(partition.size)
  156. }
  157. infos = []
  158. try:
  159. for i in info:
  160. infos += [info_dict[i]]
  161. except KeyError:
  162. raise RuntimeError("Request for unknown partition info {}".format(i))
  163. print(" ".join(infos))
  164. def main():
  165. global quiet
  166. parser = argparse.ArgumentParser("ESP-IDF Partitions Tool")
  167. parser.add_argument("--quiet", "-q", help="suppress stderr messages", action="store_true")
  168. parser.add_argument("--esptool-args", help="additional main arguments for esptool", nargs="+")
  169. parser.add_argument("--esptool-write-args", help="additional subcommand arguments when writing to flash", nargs="+")
  170. parser.add_argument("--esptool-read-args", help="additional subcommand arguments when reading flash", nargs="+")
  171. parser.add_argument("--esptool-erase-args", help="additional subcommand arguments when erasing regions of flash", nargs="+")
  172. # By default the device attached to the specified port is queried for the partition table. If a partition table file
  173. # is specified, that is used instead.
  174. 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 \
  175. when the partition table file is not defined")
  176. parser.add_argument("--baud", "-b", help="baudrate to use", type=int)
  177. parser.add_argument("--partition-table-offset", "-o", help="offset to read the partition table from", type=str)
  178. parser.add_argument("--partition-table-file", "-f", help="file (CSV/binary) to read the partition table from; \
  179. overrides device attached to specified port as the partition table source when defined")
  180. partition_selection_parser = argparse.ArgumentParser(add_help=False)
  181. # Specify what partition to perform the operation on. This can either be specified using the
  182. # partition name or the first partition that matches the specified type/subtype
  183. partition_selection_args = partition_selection_parser.add_mutually_exclusive_group()
  184. partition_selection_args.add_argument("--partition-name", "-n", help="name of the partition")
  185. partition_selection_args.add_argument("--partition-type", "-t", help="type of the partition")
  186. partition_selection_args.add_argument('--partition-boot-default', "-d", help='select the default boot partition \
  187. using the same fallback logic as the IDF bootloader', action="store_true")
  188. partition_selection_parser.add_argument("--partition-subtype", "-s", help="subtype of the partition")
  189. subparsers = parser.add_subparsers(dest="operation", help="run parttool -h for additional help")
  190. # Specify the supported operations
  191. read_part_subparser = subparsers.add_parser("read_partition", help="read partition from device and dump contents into a file",
  192. parents=[partition_selection_parser])
  193. read_part_subparser.add_argument("--output", help="file to dump the read partition contents to")
  194. write_part_subparser = subparsers.add_parser("write_partition", help="write contents of a binary file to partition on device",
  195. parents=[partition_selection_parser])
  196. write_part_subparser.add_argument("--input", help="file whose contents are to be written to the partition offset")
  197. subparsers.add_parser("erase_partition", help="erase the contents of a partition on the device", parents=[partition_selection_parser])
  198. print_partition_info_subparser = subparsers.add_parser("get_partition_info", help="get partition information", parents=[partition_selection_parser])
  199. print_partition_info_subparser.add_argument("--info", help="type of partition information to get",
  200. choices=["offset", "size"], default=["offset", "size"], nargs="+")
  201. args = parser.parse_args()
  202. quiet = args.quiet
  203. # No operation specified, display help and exit
  204. if args.operation is None:
  205. if not quiet:
  206. parser.print_help()
  207. sys.exit(1)
  208. # Prepare the partition to perform operation on
  209. if args.partition_name:
  210. partition_id = PartitionName(args.partition_name)
  211. elif args.partition_type:
  212. if not args.partition_subtype:
  213. raise RuntimeError("--partition-subtype should be defined when --partition-type is defined")
  214. partition_id = PartitionType(args.partition_type, args.partition_subtype)
  215. elif args.partition_boot_default:
  216. partition_id = PARTITION_BOOT_DEFAULT
  217. else:
  218. raise RuntimeError("Partition to operate on should be defined using --partition-name OR \
  219. partition-type,--partition-subtype OR partition-boot-default")
  220. # Prepare the device to perform operation on
  221. target_args = {}
  222. if args.port:
  223. target_args["port"] = args.port
  224. if args.baud:
  225. target_args["baud"] = args.baud
  226. if args.partition_table_file:
  227. target_args["partition_table_file"] = args.partition_table_file
  228. if args.partition_table_offset:
  229. target_args["partition_table_offset"] = int(args.partition_table_offset, 0)
  230. if args.esptool_args:
  231. target_args["esptool_args"] = args.esptool_args
  232. if args.esptool_write_args:
  233. target_args["esptool_write_args"] = args.esptool_write_args
  234. if args.esptool_read_args:
  235. target_args["esptool_read_args"] = args.esptool_read_args
  236. if args.esptool_erase_args:
  237. target_args["esptool_erase_args"] = args.esptool_erase_args
  238. target = ParttoolTarget(**target_args)
  239. # Create the operation table and execute the operation
  240. common_args = {'target':target, 'partition_id':partition_id}
  241. parttool_ops = {
  242. 'erase_partition':(_erase_partition, []),
  243. 'read_partition':(_read_partition, ["output"]),
  244. 'write_partition':(_write_partition, ["input"]),
  245. 'get_partition_info':(_get_partition_info, ["info"])
  246. }
  247. (op, op_args) = parttool_ops[args.operation]
  248. for op_arg in op_args:
  249. common_args.update({op_arg:vars(args)[op_arg]})
  250. if quiet:
  251. # If exceptions occur, suppress and exit quietly
  252. try:
  253. op(**common_args)
  254. except Exception:
  255. sys.exit(2)
  256. else:
  257. try:
  258. op(**common_args)
  259. except gen.InputError as e:
  260. print(e, file=sys.stderr)
  261. sys.exit(2)
  262. if __name__ == '__main__':
  263. main()