generation.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. #
  2. # SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
  3. # SPDX-License-Identifier: Apache-2.0
  4. #
  5. import collections
  6. import fnmatch
  7. import itertools
  8. from collections import namedtuple
  9. from entity import Entity
  10. from fragments import Mapping, Scheme, Sections
  11. from ldgen_common import LdGenFailure
  12. from output_commands import AlignAtAddress, InputSectionDesc, SymbolAtAddress
  13. class Placement():
  14. """
  15. A Placement is an assignment of an entity's input sections to a target
  16. in the output linker script - a precursor to the input section description.
  17. A placement can be excluded from another placement. These are represented
  18. as contents of EXCLUDE_FILE in the input section description. Since the linker uses the
  19. first matching rule, these exclusions make sure that accidental matching
  20. of entities with higher specificity does not occur.
  21. The placement which a placement is excluded from is referred to as the
  22. 'basis' placement. It operates on the same input section of the entity on
  23. one of the parent (or parent's parent and so forth), but might have
  24. a different target (see is_significant() for the criteria).
  25. A placement is explicit if it was derived from an actual entry in one of
  26. the mapping fragments. Just as intermediate entity nodes are created in some cases,
  27. intermediate placements are created particularly for symbol placements.
  28. The reason is that EXCLUDE_FILE does not work on symbols (see ObjectNode
  29. for details).
  30. """
  31. def __init__(self, node, sections, target, flags, explicit, force=False, dryrun=False):
  32. self.node = node
  33. self.sections = sections
  34. self.target = target
  35. self.flags = flags
  36. self.exclusions = set()
  37. self.subplacements = set()
  38. # Force this placement to be output
  39. self.force = force
  40. # This placement was created from a mapping
  41. # fragment entry.
  42. self.explicit = explicit
  43. # Find basis placement.
  44. parent = node.parent
  45. candidate = None
  46. while parent:
  47. try:
  48. candidate = parent.placements[sections]
  49. except KeyError:
  50. pass
  51. if candidate and candidate.is_significant():
  52. break
  53. else:
  54. parent = parent.parent
  55. self.basis = candidate
  56. if self.is_significant() and not dryrun and self.basis:
  57. self.basis.add_exclusion(self)
  58. def is_significant(self):
  59. # Check if the placement is significant. Significant placements
  60. # are the end of a basis chain (not self.basis) or a change
  61. # in target (self.target != self.basis.target)
  62. #
  63. # Placement can also be a basis if it has flags
  64. # (self.flags) or its basis has flags (self.basis.flags)
  65. return (not self.basis or
  66. self.target != self.basis.target or
  67. (self.flags and not self.basis.flags) or
  68. (not self.flags and self.basis.flags) or
  69. self.force)
  70. def force_significant(self):
  71. if not self.is_significant():
  72. self.force = True
  73. if self.basis:
  74. self.basis.add_exclusion(self)
  75. def add_exclusion(self, exclusion):
  76. self.exclusions.add(exclusion)
  77. def add_subplacement(self, subplacement):
  78. self.subplacements.add(subplacement)
  79. class EntityNode():
  80. """
  81. Node in entity tree. An EntityNode
  82. is created from an Entity (see entity.py).
  83. The entity tree has a maximum depth of 3. Nodes at different
  84. depths are derived from this class for special behavior (see
  85. RootNode, ArchiveNode, ObjectNode, SymbolNode) depending
  86. on entity specificity.
  87. Nodes for entities are inserted at the appropriate depth, creating
  88. intermediate nodes along the path if necessary. For example, a node
  89. for entity `lib1.a:obj1:sym1` needs to be inserted. If the node for `lib1:obj1`
  90. does not exist, then it needs to be created.
  91. A node contains a dictionary of placements (see Placement).
  92. The key to this dictionary are contents of sections fragments,
  93. representing the input sections of an entity. For example,
  94. a node for entity `lib1.a` might have a placement entry for its `.text` input section
  95. in this dictionary. The placement will contain details about the
  96. target, the flags, etc.
  97. Generation of output commands to be written to the output linker script
  98. requires traversal of the tree, each node collecting the output commands
  99. from its children, so on and so forth.
  100. """
  101. def __init__(self, parent, name):
  102. self.children = []
  103. self.parent = parent
  104. self.name = name
  105. self.child_t = EntityNode
  106. self.entity = None
  107. self.placements = dict()
  108. def add_child(self, entity):
  109. child_specificity = self.entity.specificity.value + 1
  110. assert(child_specificity <= Entity.Specificity.SYMBOL.value)
  111. name = entity[Entity.Specificity(child_specificity)]
  112. assert(name and name != Entity.ALL)
  113. child = [c for c in self.children if c.name == name]
  114. assert(len(child) <= 1)
  115. if not child:
  116. child = self.child_t(self, name)
  117. self.children.append(child)
  118. else:
  119. child = child[0]
  120. return child
  121. def get_output_commands(self):
  122. commands = collections.defaultdict(list)
  123. def process_commands(cmds):
  124. for (target, commands_list) in cmds.items():
  125. commands[target].extend(commands_list)
  126. # Process the commands generated from this node
  127. node_commands = self.get_node_output_commands()
  128. process_commands(node_commands)
  129. # Process the commands generated from this node's children
  130. # recursively
  131. for child in sorted(self.children, key=lambda c: c.name):
  132. children_commands = child.get_output_commands()
  133. process_commands(children_commands)
  134. return commands
  135. def get_node_output_commands(self):
  136. commands = collections.defaultdict(list)
  137. for sections in self.get_output_sections():
  138. placement = self.placements[sections]
  139. if placement.is_significant():
  140. assert(placement.node == self)
  141. keep = False
  142. sort = None
  143. surround_type = []
  144. placement_flags = placement.flags if placement.flags is not None else []
  145. for flag in placement_flags:
  146. if isinstance(flag, Mapping.Keep):
  147. keep = True
  148. elif isinstance(flag, Mapping.Sort):
  149. sort = (flag.first, flag.second)
  150. else: # SURROUND or ALIGN
  151. surround_type.append(flag)
  152. for flag in surround_type:
  153. if flag.pre:
  154. if isinstance(flag, Mapping.Surround):
  155. commands[placement.target].append(SymbolAtAddress('_%s_start' % flag.symbol))
  156. else: # ALIGN
  157. commands[placement.target].append(AlignAtAddress(flag.alignment))
  158. # This is for expanded object node and symbol node placements without checking for
  159. # the type.
  160. placement_sections = frozenset(placement.sections)
  161. command_sections = sections if sections == placement_sections else placement_sections
  162. command = InputSectionDesc(placement.node.entity, command_sections, [e.node.entity for e in placement.exclusions], keep, sort)
  163. commands[placement.target].append(command)
  164. # Generate commands for intermediate, non-explicit exclusion placements here, so that they can be enclosed by
  165. # flags that affect the parent placement.
  166. for subplacement in placement.subplacements:
  167. if not subplacement.flags and not subplacement.explicit:
  168. command = InputSectionDesc(subplacement.node.entity, subplacement.sections,
  169. [e.node.entity for e in subplacement.exclusions], keep, sort)
  170. commands[placement.target].append(command)
  171. for flag in surround_type:
  172. if flag.post:
  173. if isinstance(flag, Mapping.Surround):
  174. commands[placement.target].append(SymbolAtAddress('_%s_end' % flag.symbol))
  175. else: # ALIGN
  176. commands[placement.target].append(AlignAtAddress(flag.alignment))
  177. return commands
  178. def self_placement(self, sections, target, flags, explicit=True, force=False):
  179. placement = Placement(self, sections, target, flags, explicit, force)
  180. self.placements[sections] = placement
  181. return placement
  182. def child_placement(self, entity, sections, target, flags, sections_db):
  183. child = self.add_child(entity)
  184. child.insert(entity, sections, target, flags, sections_db)
  185. def insert(self, entity, sections, target, flags, sections_db):
  186. if self.entity.specificity == entity.specificity:
  187. # Since specificities match, create the placement in this node.
  188. self.self_placement(sections, target, flags)
  189. else:
  190. # If not, create a child node and try to create the placement there.
  191. self.child_placement(entity, sections, target, flags, sections_db)
  192. def get_output_sections(self):
  193. return sorted(self.placements.keys(), key=lambda x: sorted(x)) # pylint: disable=W0108
  194. class SymbolNode(EntityNode):
  195. """
  196. Entities at depth=3. Represents entities with archive, object
  197. and symbol specified.
  198. """
  199. def __init__(self, parent, name):
  200. EntityNode.__init__(self, parent, name)
  201. self.entity = Entity(self.parent.parent.name, self.parent.name)
  202. class ObjectNode(EntityNode):
  203. """
  204. Entities at depth=2. Represents entities with archive
  205. and object specified.
  206. Creating a placement on a child node (SymbolNode) has a different behavior, since
  207. exclusions using EXCLUDE_FILE for symbols does not work.
  208. The sections of this entity has to be 'expanded'. That is, we must
  209. look into the actual input sections of this entity and remove
  210. the ones corresponding to the symbol. The remaining sections of an expanded
  211. object entity will be listed one-by-one in the corresponding
  212. input section description.
  213. An intermediate placement on this node is created, if one does not exist,
  214. and is the one excluded from its basis placement.
  215. """
  216. def __init__(self, parent, name):
  217. EntityNode.__init__(self, parent, name)
  218. self.child_t = SymbolNode
  219. self.entity = Entity(self.parent.name, self.name)
  220. self.subplacements = list()
  221. def child_placement(self, entity, sections, target, flags, sections_db):
  222. child = self.add_child(entity)
  223. sym_placement = Placement(child, sections, target, flags, True, dryrun=True)
  224. # The basis placement for sym_placement can either be
  225. # an existing placement on this node, or nonexistent.
  226. if sym_placement.is_significant():
  227. try:
  228. obj_sections = self.placements[sections].sections
  229. except KeyError:
  230. obj_sections = None
  231. if not obj_sections or obj_sections == sections:
  232. # Expand this section for the first time
  233. found_sections = sections_db.get_sections(self.parent.name, self.name)
  234. obj_sections = []
  235. for s in sections:
  236. obj_sections.extend(fnmatch.filter(found_sections, s))
  237. if obj_sections:
  238. symbol = entity.symbol
  239. remove_sections = [s.replace('.*', '.%s' % symbol) for s in sections if '.*' in s]
  240. filtered_sections = [s for s in obj_sections if s not in remove_sections]
  241. if set(filtered_sections) != set(obj_sections):
  242. if sym_placement.basis:
  243. subplace = False
  244. try:
  245. # If existing placement exists, make sure that
  246. # it is emitted.
  247. obj_placement = self.placements[sections]
  248. except KeyError:
  249. # Create intermediate placement.
  250. obj_placement = self.self_placement(sections, sym_placement.basis.target, None, False)
  251. if obj_placement.basis.flags:
  252. subplace = True
  253. if subplace:
  254. obj_placement.basis.add_subplacement(obj_placement)
  255. self.subplacements.append(sections)
  256. else:
  257. obj_placement.force_significant()
  258. obj_placement.sections = filtered_sections
  259. sym_placement.basis = obj_placement
  260. sym_placement.sections = remove_sections
  261. child.placements[sections] = sym_placement
  262. def get_output_sections(self):
  263. output_sections = [key for key in self.placements if key not in self.subplacements]
  264. return sorted(output_sections, key=' '.join)
  265. class ArchiveNode(EntityNode):
  266. """
  267. Entities at depth=1. Represents entities with archive specified.
  268. """
  269. def __init__(self, parent, name):
  270. EntityNode.__init__(self, parent, name)
  271. self.child_t = ObjectNode
  272. self.entity = Entity(self.name)
  273. class RootNode(EntityNode):
  274. """
  275. Single entity at depth=0. Represents entities with no specific members
  276. specified.
  277. """
  278. def __init__(self):
  279. EntityNode.__init__(self, None, Entity.ALL)
  280. self.child_t = ArchiveNode
  281. self.entity = Entity(Entity.ALL)
  282. class Generation:
  283. """
  284. Processes all fragments processed from fragment files included in the build.
  285. Generates output commands (see output_commands.py) that LinkerScript (see linker_script.py) can
  286. write to the output linker script.
  287. """
  288. # Processed mapping, scheme and section entries
  289. EntityMapping = namedtuple('EntityMapping', 'entity sections_group target flags')
  290. def __init__(self, check_mappings=False, check_mapping_exceptions=None):
  291. self.schemes = {}
  292. self.placements = {}
  293. self.mappings = {}
  294. self.check_mappings = check_mappings
  295. if check_mapping_exceptions:
  296. self.check_mapping_exceptions = check_mapping_exceptions
  297. else:
  298. self.check_mapping_exceptions = []
  299. def _prepare_scheme_dictionary(self):
  300. scheme_dictionary = collections.defaultdict(dict)
  301. # Collect sections into buckets based on target name
  302. for scheme in self.schemes.values():
  303. sections_bucket = collections.defaultdict(list)
  304. for (sections_name, target_name) in scheme.entries:
  305. # Get the sections under the bucket 'target_name'. If this bucket does not exist
  306. # is is created automatically
  307. sections_in_bucket = sections_bucket[target_name]
  308. try:
  309. sections = self.placements[sections_name]
  310. except KeyError:
  311. message = GenerationException.UNDEFINED_REFERENCE + " to sections '" + sections_name + "'."
  312. raise GenerationException(message, scheme)
  313. sections_in_bucket.append(sections)
  314. scheme_dictionary[scheme.name] = sections_bucket
  315. # Search for and raise exception on first instance of sections mapped to multiple targets
  316. for (scheme_name, sections_bucket) in scheme_dictionary.items():
  317. for sections_a, sections_b in itertools.combinations(sections_bucket.values(), 2):
  318. set_a = set()
  319. set_b = set()
  320. for sections in sections_a:
  321. set_a.update(sections.entries)
  322. for sections in sections_b:
  323. set_b.update(sections.entries)
  324. intersection = set_a.intersection(set_b)
  325. # If the intersection is a non-empty set, it means sections are mapped to multiple
  326. # targets. Raise exception.
  327. if intersection:
  328. scheme = self.schemes[scheme_name]
  329. message = 'Sections ' + str(intersection) + ' mapped to multiple targets.'
  330. raise GenerationException(message, scheme)
  331. return scheme_dictionary
  332. def _prepare_entity_mappings(self, scheme_dictionary, entities):
  333. # Prepare entity mappings processed from mapping fragment entries.
  334. def get_section_strs(section):
  335. s_list = [Sections.get_section_data_from_entry(s) for s in section.entries]
  336. return frozenset([item for sublist in s_list for item in sublist])
  337. entity_mappings = dict()
  338. for mapping in self.mappings.values():
  339. archive = mapping.archive
  340. for (obj, symbol, scheme_name) in mapping.entries:
  341. entity = Entity(archive, obj, symbol)
  342. # Check the entity exists
  343. if (self.check_mappings and
  344. entity.specificity.value > Entity.Specificity.ARCHIVE.value and
  345. mapping.name not in self.check_mapping_exceptions):
  346. if not entities.check_exists(entity):
  347. message = "'%s' not found" % str(entity)
  348. raise GenerationException(message, mapping)
  349. if (obj, symbol, scheme_name) in mapping.flags.keys():
  350. flags = mapping.flags[(obj, symbol, scheme_name)]
  351. # Check if all section->target defined in the current
  352. # scheme.
  353. for (s, t, f) in flags:
  354. if (t not in scheme_dictionary[scheme_name].keys() or
  355. s not in [_s.name for _s in scheme_dictionary[scheme_name][t]]):
  356. message = "%s->%s not defined in scheme '%s'" % (s, t, scheme_name)
  357. raise GenerationException(message, mapping)
  358. else:
  359. flags = None
  360. # Create placement for each 'section -> target' in the scheme.
  361. for (target, sections) in scheme_dictionary[scheme_name].items():
  362. for section in sections:
  363. # Find the applicable flags
  364. _flags = []
  365. if flags:
  366. for (s, t, f) in flags:
  367. if (s, t) == (section.name, target):
  368. _flags.extend(f)
  369. sections_str = get_section_strs(section)
  370. key = (entity, section.name)
  371. try:
  372. existing = entity_mappings[key]
  373. except KeyError:
  374. existing = None
  375. if not existing:
  376. entity_mappings[key] = Generation.EntityMapping(entity, sections_str, target, _flags)
  377. else:
  378. # Check for conflicts.
  379. if (target != existing.target):
  380. raise GenerationException('Sections mapped to multiple targets.', mapping)
  381. # Combine flags here if applicable, to simplify
  382. # insertion logic.
  383. if (_flags or existing.flags):
  384. if ((_flags and not existing.flags) or (not _flags and existing.flags)):
  385. _flags.extend(existing.flags)
  386. entity_mappings[key] = Generation.EntityMapping(entity,
  387. sections_str,
  388. target, _flags)
  389. elif (_flags == existing.flags):
  390. pass
  391. else:
  392. raise GenerationException('Conflicting flags specified.', mapping)
  393. # Sort the mappings by specificity, so as to simplify
  394. # insertion logic.
  395. res = list(entity_mappings.values())
  396. res.sort(key=lambda m: m.entity)
  397. return res
  398. def generate(self, entities):
  399. scheme_dictionary = self._prepare_scheme_dictionary()
  400. entity_mappings = self._prepare_entity_mappings(scheme_dictionary, entities)
  401. root_node = RootNode()
  402. for mapping in entity_mappings:
  403. (entity, sections, target, flags) = mapping
  404. try:
  405. root_node.insert(entity, sections, target, flags, entities)
  406. except ValueError as e:
  407. raise GenerationException(str(e))
  408. # Traverse the tree, creating the placements
  409. commands = root_node.get_output_commands()
  410. return commands
  411. def add_fragments_from_file(self, fragment_file):
  412. for fragment in fragment_file.fragments:
  413. dict_to_append_to = None
  414. if isinstance(fragment, Mapping) and fragment.deprecated and fragment.name in self.mappings.keys():
  415. self.mappings[fragment.name].entries |= fragment.entries
  416. else:
  417. if isinstance(fragment, Scheme):
  418. dict_to_append_to = self.schemes
  419. elif isinstance(fragment, Sections):
  420. dict_to_append_to = self.placements
  421. else:
  422. dict_to_append_to = self.mappings
  423. # Raise exception when the fragment of the same type is already in the stored fragments
  424. if fragment.name in dict_to_append_to.keys():
  425. stored = dict_to_append_to[fragment.name].path
  426. new = fragment.path
  427. message = "Duplicate definition of fragment '%s' found in %s and %s." % (fragment.name, stored, new)
  428. raise GenerationException(message)
  429. dict_to_append_to[fragment.name] = fragment
  430. class GenerationException(LdGenFailure):
  431. """
  432. Exception for linker script generation failures such as undefined references/ failure to
  433. evaluate conditions, duplicate mappings, etc.
  434. """
  435. UNDEFINED_REFERENCE = 'Undefined reference'
  436. def __init__(self, message, fragment=None):
  437. self.fragment = fragment
  438. self.message = message
  439. def __str__(self):
  440. if self.fragment:
  441. return "%s\nIn fragment '%s' defined in '%s'." % (self.message, self.fragment.name, self.fragment.path)
  442. else:
  443. return self.message