parttool.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 gen_esp32part as gen
  26. __version__ = '1.0'
  27. IDF_COMPONENTS_PATH = os.path.expandvars(os.path.join("$IDF_PATH", "components"))
  28. ESPTOOL_PY = os.path.join(IDF_COMPONENTS_PATH, "esptool_py", "esptool", "esptool.py")
  29. quiet = False
  30. def status(msg):
  31. """ Print status message to stderr """
  32. if not quiet:
  33. print(msg)
  34. def _invoke_esptool(esptool_args, args):
  35. m_esptool_args = [sys.executable, ESPTOOL_PY]
  36. if args.port != "":
  37. m_esptool_args.extend(["--port", args.port])
  38. m_esptool_args.extend(esptool_args)
  39. if quiet:
  40. with open(os.devnull, "w") as fnull:
  41. subprocess.check_call(m_esptool_args, stdout=fnull, stderr=fnull)
  42. else:
  43. subprocess.check_call(m_esptool_args)
  44. def _get_partition_table(args):
  45. partition_table = None
  46. gen.offset_part_table = int(args.partition_table_offset, 0)
  47. if args.partition_table_file:
  48. status("Reading partition table from partition table file...")
  49. try:
  50. with open(args.partition_table_file, "rb") as partition_table_file:
  51. partition_table = gen.PartitionTable.from_binary(partition_table_file.read())
  52. status("Partition table read from binary file {}".format(partition_table_file.name))
  53. except (gen.InputError, TypeError):
  54. with open(args.partition_table_file, "r") as partition_table_file:
  55. partition_table_file.seek(0)
  56. partition_table = gen.PartitionTable.from_csv(partition_table_file.read())
  57. status("Partition table read from CSV file {}".format(partition_table_file.name))
  58. else:
  59. port_info = (" on port " + args.port if args.port else "")
  60. status("Reading partition table from device{}...".format(port_info))
  61. with tempfile.NamedTemporaryFile() as partition_table_file:
  62. invoke_args = ["read_flash", str(gen.offset_part_table), str(gen.MAX_PARTITION_LENGTH), partition_table_file.name]
  63. _invoke_esptool(invoke_args, args)
  64. partition_table = gen.PartitionTable.from_binary(partition_table_file.read())
  65. status("Partition table read from device" + port_info)
  66. return partition_table
  67. def _get_partition(args):
  68. partition_table = _get_partition_table(args)
  69. partition = None
  70. if args.partition_name:
  71. partition = partition_table.find_by_name(args.partition_name)
  72. elif args.partition_type and args.partition_subtype:
  73. partition = partition_table.find_by_type(args.partition_type, args.partition_subtype)
  74. elif args.partition_boot_default:
  75. search = ["factory"] + ["ota_{}".format(d) for d in range(16)]
  76. for subtype in search:
  77. partition = partition_table.find_by_type("app", subtype)
  78. if partition is not None:
  79. break
  80. else:
  81. raise RuntimeError("Invalid partition selection arguments. Specify --partition-name OR \
  82. --partition-type and --partition-subtype OR --partition--boot-default.")
  83. if partition:
  84. status("Found partition {}".format(str(partition)))
  85. return partition
  86. def _get_and_check_partition(args):
  87. partition = None
  88. partition = _get_partition(args)
  89. if not partition:
  90. raise RuntimeError("Unable to find specified partition.")
  91. return partition
  92. def write_partition(args):
  93. erase_partition(args)
  94. partition = _get_and_check_partition(args)
  95. status("Checking input file size...")
  96. with open(args.input, "rb") as input_file:
  97. content_len = len(input_file.read())
  98. if content_len != partition.size:
  99. status("File size (0x{:x}) does not match partition size (0x{:x})".format(content_len, partition.size))
  100. else:
  101. status("File size matches partition size (0x{:x})".format(partition.size))
  102. _invoke_esptool(["write_flash", str(partition.offset), args.input], args)
  103. status("Written contents of file '{}' to device at offset 0x{:x}".format(args.input, partition.offset))
  104. def read_partition(args):
  105. partition = _get_and_check_partition(args)
  106. _invoke_esptool(["read_flash", str(partition.offset), str(partition.size), args.output], args)
  107. status("Read partition contents from device at offset 0x{:x} to file '{}'".format(partition.offset, args.output))
  108. def erase_partition(args):
  109. partition = _get_and_check_partition(args)
  110. _invoke_esptool(["erase_region", str(partition.offset), str(partition.size)], args)
  111. status("Erased partition at offset 0x{:x} on device".format(partition.offset))
  112. def get_partition_info(args):
  113. partition = None
  114. if args.table:
  115. partition_table = _get_partition_table(args)
  116. if args.table.endswith(".csv"):
  117. partition_table = partition_table.to_csv()
  118. else:
  119. partition_table = partition_table.to_binary()
  120. with open(args.table, "wb") as table_file:
  121. table_file.write(partition_table)
  122. status("Partition table written to " + table_file.name)
  123. else:
  124. partition = _get_partition(args)
  125. if partition:
  126. info_dict = {
  127. "offset": '0x{:x}'.format(partition.offset),
  128. "size": '0x{:x}'.format(partition.size)
  129. }
  130. infos = []
  131. try:
  132. for info in args.info:
  133. infos += [info_dict[info]]
  134. except KeyError:
  135. raise RuntimeError("Request for unknown partition info {}".format(info))
  136. status("Requested partition information [{}]:".format(", ".join(args.info)))
  137. print(" ".join(infos))
  138. else:
  139. status("Partition not found")
  140. def generate_blank_partition_file(args):
  141. output = None
  142. stdout_binary = None
  143. partition = _get_and_check_partition(args)
  144. output = b"\xFF" * partition.size
  145. try:
  146. stdout_binary = sys.stdout.buffer # Python 3
  147. except AttributeError:
  148. stdout_binary = sys.stdout
  149. with stdout_binary if args.output == "" else open(args.output, 'wb') as f:
  150. f.write(output)
  151. status("Blank partition file '{}' generated".format(args.output))
  152. def main():
  153. global quiet
  154. parser = argparse.ArgumentParser("ESP-IDF Partitions Tool")
  155. parser.add_argument("--quiet", "-q", help="suppress stderr messages", action="store_true")
  156. # There are two possible sources for the partition table: a device attached to the host
  157. # or a partition table CSV/binary file. These sources are mutually exclusive.
  158. partition_table_info_source_args = parser.add_mutually_exclusive_group()
  159. partition_table_info_source_args.add_argument("--port", "-p", help="port where the device to read the partition table from is attached", default="")
  160. partition_table_info_source_args.add_argument("--partition-table-file", "-f", help="file (CSV/binary) to read the partition table from")
  161. parser.add_argument("--partition-table-offset", "-o", help="offset to read the partition table from", default="0x8000")
  162. # Specify what partition to perform the operation on. This can either be specified using the
  163. # partition name or the first partition that matches the specified type/subtype
  164. partition_selection_args = parser.add_mutually_exclusive_group()
  165. partition_selection_args.add_argument("--partition-name", "-n", help="name of the partition")
  166. partition_selection_args.add_argument("--partition-type", "-t", help="type of the partition")
  167. partition_selection_args.add_argument('--partition-boot-default', "-d", help='select the default boot partition \
  168. using the same fallback logic as the IDF bootloader', action="store_true")
  169. parser.add_argument("--partition-subtype", "-s", help="subtype of the partition")
  170. subparsers = parser.add_subparsers(dest="operation", help="run parttool -h for additional help")
  171. # Specify the supported operations
  172. read_part_subparser = subparsers.add_parser("read_partition", help="read partition from device and dump contents into a file")
  173. read_part_subparser.add_argument("--output", help="file to dump the read partition contents to")
  174. write_part_subparser = subparsers.add_parser("write_partition", help="write contents of a binary file to partition on device")
  175. write_part_subparser.add_argument("--input", help="file whose contents are to be written to the partition offset")
  176. subparsers.add_parser("erase_partition", help="erase the contents of a partition on the device")
  177. print_partition_info_subparser = subparsers.add_parser("get_partition_info", help="get partition information")
  178. print_partition_info_subparser_info_type = print_partition_info_subparser.add_mutually_exclusive_group()
  179. print_partition_info_subparser_info_type.add_argument("--info", help="type of partition information to get", nargs="+")
  180. print_partition_info_subparser_info_type.add_argument("--table", help="dump the partition table to a file")
  181. generate_blank_subparser = subparsers.add_parser("generate_blank_partition_file", help="generate a blank (all 0xFF) partition file of \
  182. the specified partition that can be flashed to the device")
  183. generate_blank_subparser.add_argument("--output", help="blank partition file filename")
  184. args = parser.parse_args()
  185. quiet = args.quiet
  186. # No operation specified, display help and exit
  187. if args.operation is None:
  188. if not quiet:
  189. parser.print_help()
  190. sys.exit(1)
  191. # Else execute the operation
  192. operation_func = globals()[args.operation]
  193. if quiet:
  194. # If exceptions occur, suppress and exit quietly
  195. try:
  196. operation_func(args)
  197. except Exception:
  198. sys.exit(2)
  199. else:
  200. operation_func(args)
  201. if __name__ == '__main__':
  202. main()