Code Generation With Jinja2


Mate Toth-Pal


Arm Limited


Mate Toth-Pal <>

Generating files from templates in TF-M

Some of the files in TF-M are generated from template files. The files to be generated are listed in tools/tfm_generated_file_list.yaml. For each generated file <path_to_file>/<filename> the template file is <path_to_file>/<filename>.template. The templates are populated with partition information from the partition manifests. The manifests to be used for the generation are listed in tools/tfm_manifest_list.yaml.

Custom generator script - Current method

tools/ Python script is used to generate files from the templates. This script calls the tools/ to parse the template files, and uses tools/ to substitute the keychains with actual values from the manifest files.

Use Jinja2 template engine - proposal

The proposal is to eliminate the template parser and substituter scripts, and call the Jinja2 template engine library from tools/ to do the substitution.

More information on jinja2:

Changes needed:

  • tools/ have to be modified to call the Jinja2 library instead of the custom scripts. The data structure required by the library is very similar to the one required by the current scripts.

  • template files needs to be rewritten to the Jinja syntax: The control characters to be replaced (like @! -> {%) and for statements to be added to iterate over the substitutions.

Improvements over the current solution

  • Compatible with Python 2.7 and Python 3, while current solution only supports Python 2.7

  • More advanced functionality: direct control over the list of items for a keychain, meta information on that list (like length)

  • Well documented (see website)

  • Jinja2 is free and open-source software, BSD licensed, just like TF-M. It is a well established software in contrast with the current proprietary solution.


Below code snippet enumerates services in Secure Partitions:

{% for partition in partitions %}
    {% if %}
        {% for service in %}
            {do something for the service}
        {% endfor %}
    {% endif %}
{% endfor %}

Copyright (c) 2019-2021, Arm Limited. All rights reserved.