parttool.py 11 KB

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