image.py 12 KB

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