image.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # Class for an image, the output of binman
  6. #
  7. from __future__ import print_function
  8. from collections import OrderedDict
  9. from operator import attrgetter
  10. import re
  11. import sys
  12. import fdt_util
  13. import tools
  14. class Image:
  15. """A Image, representing an output from binman
  16. An image is comprised of a collection of entries each containing binary
  17. data. The image size must be large enough to hold all of this data.
  18. This class implements the various operations needed for images.
  19. Atrtributes:
  20. _node: Node object that contains the image definition in device tree
  21. _name: Image name
  22. _size: Image size in bytes, or None if not known yet
  23. _align_size: Image size alignment, or None
  24. _pad_before: Number of bytes before the first entry starts. This
  25. effectively changes the place where entry position 0 starts
  26. _pad_after: Number of bytes after the last entry ends. The last
  27. entry will finish on or before this boundary
  28. _pad_byte: Byte to use to pad the image where there is no entry
  29. _filename: Output filename for image
  30. _sort: True if entries should be sorted by position, False if they
  31. must be in-order in the device tree description
  32. _skip_at_start: Number of bytes before the first entry starts. These
  33. effecively adjust the starting position of entries. For example,
  34. if _pad_before is 16, then the first entry would start at 16.
  35. An entry with pos = 20 would in fact be written at position 4
  36. in the image file.
  37. _end_4gb: Indicates that the image ends at the 4GB boundary. This is
  38. used for x86 images, which want to use positions such that a
  39. memory address (like 0xff800000) is the first entry position.
  40. This causes _skip_at_start to be set to the starting memory
  41. address.
  42. _entries: OrderedDict() of entries
  43. """
  44. def __init__(self, name, node, test=False):
  45. global entry
  46. global Entry
  47. import entry
  48. from entry import Entry
  49. self._node = node
  50. self._name = name
  51. self._size = None
  52. self._align_size = None
  53. self._pad_before = 0
  54. self._pad_after = 0
  55. self._pad_byte = 0
  56. self._filename = '%s.bin' % self._name
  57. self._sort = False
  58. self._skip_at_start = 0
  59. self._end_4gb = False
  60. self._entries = OrderedDict()
  61. if not test:
  62. self._ReadNode()
  63. self._ReadEntries()
  64. def _ReadNode(self):
  65. """Read properties from the image node"""
  66. self._size = fdt_util.GetInt(self._node, 'size')
  67. self._align_size = fdt_util.GetInt(self._node, 'align-size')
  68. if tools.NotPowerOfTwo(self._align_size):
  69. self._Raise("Alignment size %s must be a power of two" %
  70. self._align_size)
  71. self._pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  72. self._pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  73. self._pad_byte = fdt_util.GetInt(self._node, 'pad-byte', 0)
  74. filename = fdt_util.GetString(self._node, 'filename')
  75. if filename:
  76. self._filename = filename
  77. self._sort = fdt_util.GetBool(self._node, 'sort-by-pos')
  78. self._end_4gb = fdt_util.GetBool(self._node, 'end-at-4gb')
  79. if self._end_4gb and not self._size:
  80. self._Raise("Image size must be provided when using end-at-4gb")
  81. if self._end_4gb:
  82. self._skip_at_start = 0x100000000 - self._size
  83. def CheckSize(self):
  84. """Check that the image contents does not exceed its size, etc."""
  85. contents_size = 0
  86. for entry in self._entries.values():
  87. contents_size = max(contents_size, entry.pos + entry.size)
  88. contents_size -= self._skip_at_start
  89. size = self._size
  90. if not size:
  91. size = self._pad_before + contents_size + self._pad_after
  92. size = tools.Align(size, self._align_size)
  93. if self._size and contents_size > self._size:
  94. self._Raise("contents size %#x (%d) exceeds image size %#x (%d)" %
  95. (contents_size, contents_size, self._size, self._size))
  96. if not self._size:
  97. self._size = size
  98. if self._size != tools.Align(self._size, self._align_size):
  99. self._Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  100. (self._size, self._size, self._align_size, self._align_size))
  101. def _Raise(self, msg):
  102. """Raises an error for this image
  103. Args:
  104. msg: Error message to use in the raise string
  105. Raises:
  106. ValueError()
  107. """
  108. raise ValueError("Image '%s': %s" % (self._node.path, msg))
  109. def GetPath(self):
  110. """Get the path of an image (in the FDT)
  111. Returns:
  112. Full path of the node for this image
  113. """
  114. return self._node.path
  115. def _ReadEntries(self):
  116. for node in self._node.subnodes:
  117. self._entries[node.name] = Entry.Create(self, node)
  118. def FindEntryType(self, etype):
  119. """Find an entry type in the image
  120. Args:
  121. etype: Entry type to find
  122. Returns:
  123. entry matching that type, or None if not found
  124. """
  125. for entry in self._entries.values():
  126. if entry.etype == etype:
  127. return entry
  128. return None
  129. def GetEntryContents(self):
  130. """Call ObtainContents() for each entry
  131. This calls each entry's ObtainContents() a few times until they all
  132. return True. We stop calling an entry's function once it returns
  133. True. This allows the contents of one entry to depend on another.
  134. After 3 rounds we give up since it's likely an error.
  135. """
  136. todo = self._entries.values()
  137. for passnum in range(3):
  138. next_todo = []
  139. for entry in todo:
  140. if not entry.ObtainContents():
  141. next_todo.append(entry)
  142. todo = next_todo
  143. if not todo:
  144. break
  145. def _SetEntryPosSize(self, name, pos, size):
  146. """Set the position and size of an entry
  147. Args:
  148. name: Entry name to update
  149. pos: New position
  150. size: New size
  151. """
  152. entry = self._entries.get(name)
  153. if not entry:
  154. self._Raise("Unable to set pos/size for unknown entry '%s'" % name)
  155. entry.SetPositionSize(self._skip_at_start + pos, size)
  156. def GetEntryPositions(self):
  157. """Handle entries that want to set the position/size of other entries
  158. This calls each entry's GetPositions() method. If it returns a list
  159. of entries to update, it updates them.
  160. """
  161. for entry in self._entries.values():
  162. pos_dict = entry.GetPositions()
  163. for name, info in pos_dict.iteritems():
  164. self._SetEntryPosSize(name, *info)
  165. def PackEntries(self):
  166. """Pack all entries into the image"""
  167. pos = self._skip_at_start
  168. for entry in self._entries.values():
  169. pos = entry.Pack(pos)
  170. def _SortEntries(self):
  171. """Sort entries by position"""
  172. entries = sorted(self._entries.values(), key=lambda entry: entry.pos)
  173. self._entries.clear()
  174. for entry in entries:
  175. self._entries[entry._node.name] = entry
  176. def CheckEntries(self):
  177. """Check that entries do not overlap or extend outside the image"""
  178. if self._sort:
  179. self._SortEntries()
  180. pos = 0
  181. prev_name = 'None'
  182. for entry in self._entries.values():
  183. if (entry.pos < self._skip_at_start or
  184. entry.pos >= self._skip_at_start + self._size):
  185. entry.Raise("Position %#x (%d) is outside the image starting "
  186. "at %#x (%d)" %
  187. (entry.pos, entry.pos, self._skip_at_start,
  188. self._skip_at_start))
  189. if entry.pos < pos:
  190. entry.Raise("Position %#x (%d) overlaps with previous entry '%s' "
  191. "ending at %#x (%d)" %
  192. (entry.pos, entry.pos, prev_name, pos, pos))
  193. pos = entry.pos + entry.size
  194. prev_name = entry.GetPath()
  195. def ProcessEntryContents(self):
  196. """Call the ProcessContents() method for each entry
  197. This is intended to adjust the contents as needed by the entry type.
  198. """
  199. for entry in self._entries.values():
  200. entry.ProcessContents()
  201. def WriteSymbols(self):
  202. """Write symbol values into binary files for access at run time"""
  203. for entry in self._entries.values():
  204. entry.WriteSymbols(self)
  205. def BuildImage(self):
  206. """Write the image to a file"""
  207. fname = tools.GetOutputFilename(self._filename)
  208. with open(fname, 'wb') as fd:
  209. fd.write(chr(self._pad_byte) * self._size)
  210. for entry in self._entries.values():
  211. data = entry.GetData()
  212. fd.seek(self._pad_before + entry.pos - self._skip_at_start)
  213. fd.write(data)
  214. def LookupSymbol(self, sym_name, optional, msg):
  215. """Look up a symbol in an ELF file
  216. Looks up a symbol in an ELF file. Only entry types which come from an
  217. ELF image can be used by this function.
  218. At present the only entry property supported is pos.
  219. Args:
  220. sym_name: Symbol name in the ELF file to look up in the format
  221. _binman_<entry>_prop_<property> where <entry> is the name of
  222. the entry and <property> is the property to find (e.g.
  223. _binman_u_boot_prop_pos). As a special case, you can append
  224. _any to <entry> to have it search for any matching entry. E.g.
  225. _binman_u_boot_any_prop_pos will match entries called u-boot,
  226. u-boot-img and u-boot-nodtb)
  227. optional: True if the symbol is optional. If False this function
  228. will raise if the symbol is not found
  229. msg: Message to display if an error occurs
  230. Returns:
  231. Value that should be assigned to that symbol, or None if it was
  232. optional and not found
  233. Raises:
  234. ValueError if the symbol is invalid or not found, or references a
  235. property which is not supported
  236. """
  237. m = re.match(r'^_binman_(\w+)_prop_(\w+)$', sym_name)
  238. if not m:
  239. raise ValueError("%s: Symbol '%s' has invalid format" %
  240. (msg, sym_name))
  241. entry_name, prop_name = m.groups()
  242. entry_name = entry_name.replace('_', '-')
  243. entry = self._entries.get(entry_name)
  244. if not entry:
  245. if entry_name.endswith('-any'):
  246. root = entry_name[:-4]
  247. for name in self._entries:
  248. if name.startswith(root):
  249. rest = name[len(root):]
  250. if rest in ['', '-img', '-nodtb']:
  251. entry = self._entries[name]
  252. if not entry:
  253. err = ("%s: Entry '%s' not found in list (%s)" %
  254. (msg, entry_name, ','.join(self._entries.keys())))
  255. if optional:
  256. print('Warning: %s' % err, file=sys.stderr)
  257. return None
  258. raise ValueError(err)
  259. if prop_name == 'pos':
  260. return entry.pos
  261. else:
  262. raise ValueError("%s: No such property '%s'" % (msg, prop_name))