linker-script-generation.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. Linker Script Generation
  2. ========================
  3. :link_to_translation:`zh_CN:[中文]`
  4. Overview
  5. --------
  6. There are several :ref:`memory regions<memory-layout>` where code and data can be placed. Code and read-only data are placed by default in flash,
  7. writable data in RAM, etc. However, it is sometimes necessary to change these default placements. For example, it may
  8. be necessary to place critical code in RAM for performance reasons or to place code in RTC memory for use in a wake stub or the ULP coprocessor.
  9. With the linker script generation mechanism, it is possible to specify these placements at the component level within ESP-IDF. The component presents
  10. information on how it would like to place its symbols, objects or the entire archive. During build the information presented by the components are collected,
  11. parsed and processed; and the placement rules generated is used to link the app.
  12. Quick Start
  13. ------------
  14. This section presents a guide for quickly placing code/data to RAM and RTC memory - placements ESP-IDF provides out-of-the-box.
  15. For this guide, suppose we have the following::
  16. - components/
  17. - my_component/
  18. - CMakeLists.txt
  19. - component.mk
  20. - Kconfig
  21. - src/
  22. - my_src1.c
  23. - my_src2.c
  24. - my_src3.c
  25. - my_linker_fragment_file.lf
  26. - a component named ``my_component`` that is archived as library ``libmy_component.a`` during build
  27. - three source files archived under the library, ``my_src1.c``, ``my_src2.c`` and ``my_src3.c`` which are compiled as ``my_src1.o``, ``my_src2.o`` and ``my_src3.o``, respectively
  28. - under ``my_src1.o``, the function ``my_function1`` is defined; under ``my_src2.o``, the function ``my_function2`` is defined
  29. - there exist bool-type config ``PERFORMANCE_MODE`` (y/n) and int type config ``PERFORMANCE_LEVEL`` (with range 0-3) in ``my_component``'s Kconfig
  30. Creating and Specifying a Linker Fragment File
  31. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  32. Before anything else, a linker fragment file needs to be created. A linker fragment file
  33. is simply a text file with a ``.lf`` extension upon which the desired placements will be written.
  34. After creating the file, it is then necessary to present it to the build system. The instructions for the build systems
  35. supported by ESP-IDF are as follows:
  36. Make
  37. """"
  38. In the component's ``component.mk`` file, set the variable ``COMPONENT_ADD_LDFRAGMENTS`` to the path of the created linker
  39. fragment file. The path can either be an absolute path or a relative path from the component directory.
  40. .. code-block:: make
  41. COMPONENT_ADD_LDFRAGMENTS += my_linker_fragment_file.lf
  42. CMake
  43. """""
  44. In the component's ``CMakeLists.txt`` file, specify argument ``LDFRAGMENTS`` in the ``idf_component_register`` call.
  45. The value of ``LDFRAGMENTS`` can either be an absolute path or a relative path from the component directory to the
  46. created linker fragment file.
  47. .. code-block:: cmake
  48. # file paths relative to CMakeLists.txt
  49. idf_component_register(...
  50. LDFRAGMENTS "path/to/linker_fragment_file.lf" "path/to/another_linker_fragment_file.lf"
  51. ...
  52. )
  53. Specifying placements
  54. ^^^^^^^^^^^^^^^^^^^^^
  55. It is possible to specify placements at the following levels of granularity:
  56. - object file (``.obj`` or ``.o`` files)
  57. - symbol (function/variable)
  58. - archive (``.a`` files)
  59. .. _ldgen-placing-object-files :
  60. Placing object files
  61. """"""""""""""""""""
  62. Suppose the entirety of ``my_src1.o`` is performance-critical, so it is desirable to place it in RAM.
  63. On the other hand, the entirety of ``my_src2.o`` contains symbols needed coming out of deep sleep, so it needs to be put under RTC memory.
  64. In the the linker fragment file, we can write:
  65. .. code-block:: none
  66. [mapping:my_component]
  67. archive: libmy_component.a
  68. entries:
  69. my_src1 (noflash) # places all my_src1 code/read-only data under IRAM/DRAM
  70. my_src2 (rtc) # places all my_src2 code/ data and read-only data under RTC fast memory/RTC slow memory
  71. What happens to ``my_src3.o``? Since it is not specified, default placements are used for ``my_src3.o``. More on default placements
  72. :ref:`here<ldgen-default-placements>`.
  73. Placing symbols
  74. """"""""""""""""
  75. Continuing our example, suppose that among functions defined under ``object1.o``, only ``my_function1`` is performance-critical; and under ``object2.o``,
  76. only ``my_function2`` needs to execute after the chip comes out of deep sleep. This could be accomplished by writing:
  77. .. code-block:: none
  78. [mapping:my_component]
  79. archive: libmy_component.a
  80. entries:
  81. my_src1:my_function1 (noflash)
  82. my_src2:my_function2 (rtc)
  83. The default placements are used for the rest of the functions in ``my_src1.o`` and ``my_src2.o`` and the entire ``object3.o``. Something similar
  84. can be achieved for placing data by writing the variable name instead of the function name, like so::
  85. my_src1:my_variable (noflash)
  86. .. warning::
  87. There are :ref:`limitations<ldgen-symbol-granularity-placements>` in placing code/data at symbol granularity. In order to ensure proper placements, an alternative would be to group
  88. relevant code and data into source files, and :ref:`use object-granularity placements<ldgen-placing-object-files>`.
  89. Placing entire archive
  90. """""""""""""""""""""""
  91. In this example, suppose that the entire component archive needs to be placed in RAM. This can be written as:
  92. .. code-block:: none
  93. [mapping:my_component]
  94. archive: libmy_component.a
  95. entries:
  96. * (noflash)
  97. Similarly, this places the entire component in RTC memory:
  98. .. code-block:: none
  99. [mapping:my_component]
  100. archive: libmy_component.a
  101. entries:
  102. * (rtc)
  103. Configuration-dependent placements
  104. """"""""""""""""""""""""""""""""""
  105. Suppose that the entire component library should only have special placement when a certain condition is true; for example, when ``CONFIG_PERFORMANCE_MODE == y``.
  106. This could be written as:
  107. .. code-block:: none
  108. [mapping:my_component]
  109. archive: libmy_component.a
  110. entries:
  111. if PERFORMANCE_MODE = y:
  112. * (noflash)
  113. else:
  114. * (default)
  115. For a more complex config-dependent placement, suppose the following requirements: when ``CONFIG_PERFORMANCE_LEVEL == 1``, only ``object1.o`` is put in RAM;
  116. when ``CONFIG_PERFORMANCE_LEVEL == 2``, ``object1.o`` and ``object2.o``; and when ``CONFIG_PERFORMANCE_LEVEL == 3`` all object files under the archive
  117. are to be put into RAM. When these three are false however, put entire library in RTC memory. This scenario is a bit contrived, but,
  118. it can be written as:
  119. .. code-block:: none
  120. [mapping:my_component]
  121. archive: libmy_component.a
  122. entries:
  123. if PERFORMANCE_LEVEL = 1:
  124. my_src1 (noflash)
  125. elif PERFORMANCE_LEVEL = 2:
  126. my_src1 (noflash)
  127. my_src2 (noflash)
  128. elif PERFORMANCE_LEVEL = 3:
  129. my_src1 (noflash)
  130. my_src2 (noflash)
  131. my_src3 (noflash)
  132. else:
  133. * (rtc)
  134. Nesting condition-checking is also possible. The following is equivalent to the snippet above:
  135. .. code-block:: none
  136. [mapping:my_component]
  137. archive: libmy_component.a
  138. entries:
  139. if PERFORMANCE_LEVEL <= 3 && PERFORMANCE_LEVEL > 0:
  140. if PERFORMANCE_LEVEL >= 1:
  141. object1 (noflash)
  142. if PERFORMANCE_LEVEL >= 2:
  143. object2 (noflash)
  144. if PERFORMANCE_LEVEL >= 3:
  145. object2 (noflash)
  146. else:
  147. * (rtc)
  148. .. _ldgen-default-placements:
  149. The 'default' placements
  150. ^^^^^^^^^^^^^^^^^^^^^^^^
  151. Up until this point, the term 'default placements' has been mentioned as fallback placements when the
  152. placement rules ``rtc`` and ``noflash`` are not specified. It is important to note that the tokens ``noflash`` or ``rtc`` are not merely keywords, but are actually
  153. entities called fragments, specifically :ref:`schemes<ldgen-scheme-fragment>`.
  154. In the same manner as ``rtc`` and ``noflash`` are schemes, there exists a ``default`` scheme which defines what the default placement rules should be.
  155. As the name suggests, it is where code and data are usually placed, i.e. code/constants is placed in flash, variables
  156. placed in RAM, etc. More on the default scheme :ref:`here<ldgen-default-scheme>`.
  157. .. note::
  158. For an example of an ESP-IDF component using the linker script generation mechanism, see :component_file:`freertos/CMakeLists.txt`.
  159. ``freertos`` uses this to place its object files to the instruction RAM for performance reasons.
  160. This marks the end of the quick start guide. The following text discusses the internals of the mechanism in a little bit more detail.
  161. The following sections should be helpful in creating custom placements or modifying default behavior.
  162. Linker Script Generation Internals
  163. ----------------------------------
  164. Linking is the last step in the process of turning C/C++ source files into an executable. It is performed by the toolchain's linker, and accepts
  165. linker scripts which specify code/data placements, among other things. With the linker script generation mechanism, this process is no different, except
  166. that the linker script passed to the linker is dynamically generated from: (1) the collected :ref:`linker fragment files<ldgen-linker-fragment-files>` and
  167. (2) :ref:`linker script template<ldgen-linker-script-template>`.
  168. .. note::
  169. The tool that implements the linker script generation mechanism lives under :idf:`tools/ldgen`.
  170. .. _ldgen-linker-fragment-files :
  171. Linker Fragment Files
  172. ^^^^^^^^^^^^^^^^^^^^^
  173. As mentioned in the quick start guide, fragment files are simple text files with the ``.lf`` extension containing the desired placements. This is a simplified
  174. description of what fragment files contain, however. What fragment files actually contain are 'fragments'. Fragments are entities which contain pieces of information which, when put together, form
  175. placement rules that tell where to place sections of object files in the output binary. There are three types of fragments: :ref:`sections<ldgen-sections-fragment>`,
  176. :ref:`scheme<ldgen-scheme-fragment>` and :ref:`mapping<ldgen-mapping-fragment>`.
  177. Grammar
  178. """""""
  179. The three fragment types share a common grammar:
  180. .. code-block:: none
  181. [type:name]
  182. key: value
  183. key:
  184. value
  185. value
  186. value
  187. ...
  188. - type: Corresponds to the fragment type, can either be ``sections``, ``scheme`` or ``mapping``.
  189. - name: The name of the fragment, should be unique for the specified fragment type.
  190. - key, value: Contents of the fragment; each fragment type may support different keys and different grammars for the key values.
  191. .. note::
  192. In cases where multiple fragments of the same type and name are encountered, an exception is thrown.
  193. .. note::
  194. The only valid characters for fragment names and keys are alphanumeric characters and underscore.
  195. .. _ldgen-condition-checking :
  196. **Condition Checking**
  197. Condition checking enable the linker script generation to be configuration-aware. Depending on whether expressions involving configuration values
  198. are true or not, a particular set of values for a key can be used. The evaluation uses ``eval_string`` from :idf_file:`tools/kconfig_new/kconfiglib.py`
  199. and adheres to its required syntax and limitations. Supported operators are as follows:
  200. - comparison
  201. - LessThan ``<``
  202. - LessThanOrEqualTo ``<=``
  203. - MoreThan ``>``
  204. - MoreThanOrEqualTo ``>=``
  205. - Equal ``=``
  206. - NotEqual ``!=``
  207. - logical
  208. - Or ``||``
  209. - And ``&&``
  210. - Negation ``!``
  211. - grouping
  212. - Parenthesis ``()``
  213. Condition checking behaves as you would expect an ``if...elseif/elif...else`` block in other languages. Condition-checking is possible
  214. for both key values and entire fragments. The two sample fragments below are equivalent:
  215. .. code-block:: none
  216. # Value for keys is dependent on config
  217. [type:name]
  218. key_1:
  219. if CONDITION = y:
  220. value_1
  221. else:
  222. value_2
  223. key_2:
  224. if CONDITION = y:
  225. value_a
  226. else:
  227. value_b
  228. .. code-block:: none
  229. # Entire fragment definition is dependent on config
  230. if CONDITION = y:
  231. [type:name]
  232. key_1:
  233. value_1
  234. key_2:
  235. value_b
  236. else:
  237. [type:name]
  238. key_1:
  239. value_2
  240. key_2:
  241. value_b
  242. **Comments**
  243. Comment in linker fragment files begin with ``#``. Like in other languages, comment are used to provide helpful descriptions and documentation
  244. and are ignored during processing.
  245. Compatibility with ESP-IDF v3.x Linker Script Fragment Files
  246. """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
  247. ESP-IDF v4.0 brings some changes to the linker script fragment file grammar:
  248. - indentation is enforced and improperly indented fragment files generate a parse exception; this was not enforced in the old version but previous documentation and examples demonstrates properly indented grammar
  249. - move to ``if...elif...else`` structure for conditionals, with the ability to nest checks and place entire fragments themselves inside conditionals
  250. - mapping fragments now requires a name like other fragment types
  251. Linker script generator should be able to parse ESP-IDF v3.x linker fragment files that are indented properly (as demonstrated by
  252. the ESP-IDF v3.x version of this document). Backward compatibility with the previous mapping fragment grammar (optional
  253. name and the old grammar for conditionals) has also been retained but with a deprecation warning. Users should switch to the newer grammar discussed
  254. in this document as support for the old grammar is planned to be removed in the future.
  255. Note that linker fragment files using the new ESP-IDF v4.0 grammar is not supported on ESP-IDF v3.x, however.
  256. Types
  257. """""
  258. .. _ldgen-sections-fragment :
  259. **Sections**
  260. Sections fragments defines a list of object file sections that the GCC compiler emits. It may be a default section (e.g. ``.text``, ``.data``) or
  261. it may be user defined section through the ``__attribute__`` keyword.
  262. The use of an optional '+' indicates the inclusion of the section in the list, as well as sections that start with it. This is the preferred method over listing both explicitly.
  263. .. code-block:: none
  264. [sections:name]
  265. entries:
  266. .section+
  267. .section
  268. ...
  269. Example:
  270. .. code-block:: none
  271. # Non-preferred
  272. [sections:text]
  273. entries:
  274. .text
  275. .text.*
  276. .literal
  277. .literal.*
  278. # Preferred, equivalent to the one above
  279. [sections:text]
  280. entries:
  281. .text+ # means .text and .text.*
  282. .literal+ # means .literal and .literal.*
  283. .. _ldgen-scheme-fragment :
  284. **Scheme**
  285. Scheme fragments define what ``target`` a sections fragment is assigned to.
  286. .. code-block:: none
  287. [scheme:name]
  288. entries:
  289. sections -> target
  290. sections -> target
  291. ...
  292. Example:
  293. .. code-block:: none
  294. [scheme:noflash]
  295. entries:
  296. text -> iram0_text # the entries under the sections fragment named text will go to iram0_text
  297. rodata -> dram0_data # the entries under the sections fragment named rodata will go to dram0_data
  298. .. _ldgen-default-scheme:
  299. The ``default`` scheme
  300. There exists a special scheme with the name ``default``. This scheme is special because catch-all placement rules are generated from
  301. its entries. This means that, if one of its entries is ``text -> flash_text``, the placement rule
  302. .. code-block:: none
  303. *(.literal .literal.* .text .text.*)
  304. will be generated for the target ``flash_text``.
  305. These catch-all rules then effectively serve as fallback rules for those whose mappings were not specified.
  306. The ``default scheme`` is defined in :component_file:`{IDF_TARGET_PATH_NAME}/ld/{IDF_TARGET_PATH_NAME}_fragments.lf`. The ``noflash`` and ``rtc`` scheme fragments which are
  307. built-in schemes referenced in the quick start guide are also defined in this file.
  308. .. _ldgen-mapping-fragment :
  309. **Mapping**
  310. Mapping fragments define what scheme fragment to use for mappable entities, i.e. object files, function names, variable names, archives.
  311. .. code-block:: none
  312. [mapping:name]
  313. archive: archive # output archive file name, as built (i.e. libxxx.a)
  314. entries:
  315. object:symbol (scheme) # symbol granularity
  316. object (scheme) # object granularity
  317. * (scheme) # archive granularity
  318. There are three levels of placement granularity:
  319. - symbol: The object file name and symbol name are specified. The symbol name can be a function name or a variable name.
  320. - object: Only the object file name is specified.
  321. - archive: ``*`` is specified, which is a short-hand for all the object files under the archive.
  322. To know what an entry means, let us expand a sample object-granularity placement:
  323. .. code-block:: none
  324. object (scheme)
  325. Then expanding the scheme fragment from its entries definitions, we have:
  326. .. code-block:: none
  327. object (sections -> target,
  328. sections -> target,
  329. ...)
  330. Expanding the sections fragment with its entries definition:
  331. .. code-block:: none
  332. object (.section, # given this object file
  333. .section, # put its sections listed here at this
  334. ... -> target, # target
  335. .section,
  336. .section, # same should be done for these sections
  337. ... -> target,
  338. ...) # and so on
  339. Example:
  340. .. code-block:: none
  341. [mapping:map]
  342. archive: libfreertos.a
  343. entries:
  344. * (noflash)
  345. .. _ldgen-symbol-granularity-placements :
  346. On Symbol-Granularity Placements
  347. """"""""""""""""""""""""""""""""
  348. Symbol granularity placements is possible due to compiler flags ``-ffunction-sections`` and ``-ffdata-sections``. ESP-IDF compiles with these flags by default.
  349. If the user opts to remove these flags, then the symbol-granularity placements will not work. Furthermore, even with the presence of these flags, there are still other limitations to keep in mind
  350. due to the dependence on the compiler's emitted output sections.
  351. For example, with ``-ffunction-sections``, separate sections are emitted for each function; with section names predictably constructed i.e. ``.text.{func_name}``
  352. and ``.literal.{func_name}``. This is not the case for string literals within the function, as they go to pooled or generated section names.
  353. With ``-fdata-sections``, for global scope data the compiler predictably emits either ``.data.{var_name}``, ``.rodata.{var_name}`` or ``.bss.{var_name}``; and so ``Type I`` mapping entry works for these.
  354. However, this is not the case for static data declared in function scope, as the generated section name is a result of mangling the variable name with some other information.
  355. .. _ldgen-linker-script-template :
  356. Linker Script Template
  357. ^^^^^^^^^^^^^^^^^^^^^^
  358. The linker script template is the skeleton in which the generated placement rules are put into. It is an otherwise ordinary linker script, with a specific marker syntax
  359. that indicates where the generated placement rules are placed.
  360. To reference the placement rules collected under a ``target`` token, the following syntax is used:
  361. .. code-block:: none
  362. mapping[target]
  363. Example:
  364. The example below is an excerpt from a possible linker script template. It defines an output section ``.iram0.text``, and inside is a marker referencing
  365. the target ``iram0_text``.
  366. .. code-block:: none
  367. .iram0.text :
  368. {
  369. /* Code marked as runnning out of IRAM */
  370. _iram_text_start = ABSOLUTE(.);
  371. /* Marker referencing iram0_text */
  372. mapping[iram0_text]
  373. _iram_text_end = ABSOLUTE(.);
  374. } > iram0_0_seg
  375. Suppose the generator collected the fragment definitions below:
  376. .. code-block:: none
  377. [sections:text]
  378. .text+
  379. .literal+
  380. [sections:iram]
  381. .iram1+
  382. [scheme:default]
  383. entries:
  384. text -> flash_text
  385. iram -> iram0_text
  386. [scheme:noflash]
  387. entries:
  388. text -> iram0_text
  389. [mapping:freertos]
  390. archive: libfreertos.a
  391. entries:
  392. * (noflash)
  393. Then the corresponding excerpt from the generated linker script will be as follows:
  394. .. code-block:: c
  395. .iram0.text :
  396. {
  397. /* Code marked as runnning out of IRAM */
  398. _iram_text_start = ABSOLUTE(.);
  399. /* Placement rules generated from the processed fragments, placed where the marker was in the template */
  400. *(.iram1 .iram1.*)
  401. *libfreertos.a:(.literal .text .literal.* .text.*)
  402. _iram_text_end = ABSOLUTE(.);
  403. } > iram0_0_seg
  404. ``*libfreertos.a:(.literal .text .literal.* .text.*)``
  405. Rule generated from the entry ``* (noflash)`` of the ``freertos`` mapping fragment. All ``text`` sections of all
  406. object files under the archive ``libfreertos.a`` will be collected under the target ``iram0_text`` (as per the ``noflash`` scheme)
  407. and placed wherever in the template ``iram0_text`` is referenced by a marker.
  408. ``*(.iram1 .iram1.*)``
  409. Rule generated from the default scheme entry ``iram -> iram0_text``. Since the default scheme specifies an ``iram -> iram0_text`` entry,
  410. it too is placed wherever ``iram0_text`` is referenced by a marker. Since it is a rule generated from the default scheme, it comes first
  411. among all other rules collected under the same target name.
  412. The linker script template currently used is :component_file:`{IDF_TARGET_PATH_NAME}/ld/{IDF_TARGET_PATH_NAME}.project.ld.in`, specified by the ``{IDF_TARGET_PATH_NAME}`` component; the
  413. generated output script is put under its build directory.