parttool.py 14 KB

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