blob: b359f158d531ece0e352a18843b2b555d3729f14 [file] [log] [blame]
Miklos Balint470919c2018-05-22 17:51:29 +02001#-------------------------------------------------------------------------------
Xinyu Zhang90f08dc2022-01-12 15:55:17 +08002# Copyright (c) 2018-2022, Arm Limited. All rights reserved.
Miklos Balint470919c2018-05-22 17:51:29 +02003#
4# SPDX-License-Identifier: BSD-3-Clause
5#
6#-------------------------------------------------------------------------------
7
8import os
Mate Toth-Pal36f21842018-11-08 16:12:51 +01009import io
Kevin Pengce99e5d2021-11-09 18:06:53 +080010import re
Shawn Shana9ad1e02019-08-07 15:49:48 +080011import sys
12import argparse
Ken Liu1f345b02020-05-30 21:11:05 +080013from jinja2 import Environment, BaseLoader, select_autoescape, TemplateNotFound
Miklos Balint470919c2018-05-22 17:51:29 +020014
15try:
16 import yaml
17except ImportError as e:
Kevin Peng5bc82d22021-10-19 11:18:40 +080018 print (str(e) + ' To install it, type:')
19 print ('pip install PyYAML')
Miklos Balint470919c2018-05-22 17:51:29 +020020 exit(1)
21
Edison Ai48b2d9e2019-06-24 14:39:45 +080022donotedit_warning = \
Sherry Zhangf58f2bd2022-01-10 17:21:11 +080023 ' WARNING: This is an auto-generated file. Do not edit! '
Kevin Peng655f2392019-11-27 16:33:02 +080024
Kevin Pengce99e5d2021-11-09 18:06:53 +080025TFM_ROOT_DIR = os.path.join(sys.path[0], '..')
Kevin Peng655f2392019-11-27 16:33:02 +080026OUT_DIR = None # The root directory that files are generated to
Edison Ai48b2d9e2019-06-24 14:39:45 +080027
Sherry Zhang87e6d2e2021-12-27 14:48:59 +080028# PID[0, TFM_PID_BASE - 1] are reserved for TF-M SPM and test usages
Kevin Pengce99e5d2021-11-09 18:06:53 +080029TFM_PID_BASE = 256
30
Ruiqi Jiang71d361c2021-06-23 17:45:55 +010031# variable for checking for duplicated sid
32sid_list = []
Mate Toth-Pal36f21842018-11-08 16:12:51 +010033class TemplateLoader(BaseLoader):
34 """
35 Template loader class.
Miklos Balint470919c2018-05-22 17:51:29 +020036
Mate Toth-Pal36f21842018-11-08 16:12:51 +010037 An instance of this class is passed to the template engine. It is
38 responsible for reading the template file
39 """
40 def __init__(self):
41 pass
Miklos Balint470919c2018-05-22 17:51:29 +020042
Mate Toth-Pal36f21842018-11-08 16:12:51 +010043 def get_source(self, environment, template):
44 """
45 This function reads the template files.
46 For detailed documentation see:
47 http://jinja.pocoo.org/docs/2.10/api/#jinja2.BaseLoader.get_source
48
49 Please note that this function always return 'false' as 'uptodate'
50 value, so the output file will always be generated.
51 """
52 if not os.path.isfile(template):
53 raise TemplateNotFound(template)
54 with open(template) as f:
55 source = f.read()
56 return source, template, False
57
Kevin Pengce99e5d2021-11-09 18:06:53 +080058def get_single_macro_def_from_file(file_name, macro_name):
59 """
60 This function parses the given file_name to get the definition of the given
61 C Macro (macro_name).
62
63 It assumes that the target Macro has no multiple definitions in different
64 build configurations.
65
66 It supports Macros defined in multi-line, for example:
67 #define SOME_MACRO \
68 the_macro_value
69
70 Inputs:
71 - file_name: the file to get the Macro from
72 - macro_name: the name of the Macro to get
73 Returns:
74 - The Macro definition with '()' stripped, or Exception if not found
75 """
76
77 with open(file_name, 'r') as f:
78 pattern = re.compile(r'#define\s+{}[\\\s]+.*'.format(macro_name))
79 result = pattern.findall(f.read())
80
81 if len(result) != 1:
82 raise Exception('{} not defined or has multiple definitions'.format(macro_name))
83
84 macro_def = result[0].split()[-1].strip('()')
85
86 return macro_def
87
Kevin Peng8849b6a2021-11-09 14:17:35 +080088def manifest_validation(partition_manifest, pid):
Mingyang Sun294ce2e2021-06-11 11:58:24 +080089 """
90 This function validates FF-M compliance for partition manifest, and sets
91 default values for optional attributes.
Kevin Pengce99e5d2021-11-09 18:06:53 +080092 The validation is skipped for TF-M specific Partitions (PID < TFM_PID_BASE).
Mingyang Sun294ce2e2021-06-11 11:58:24 +080093 More validation items will be added.
94 """
Kevin Peng5bc82d22021-10-19 11:18:40 +080095
Kevin Peng8849b6a2021-11-09 14:17:35 +080096 service_list = partition_manifest.get('services', [])
97 irq_list = partition_manifest.get('irqs', [])
Mingyang Sun294ce2e2021-06-11 11:58:24 +080098
Kevin Pengce99e5d2021-11-09 18:06:53 +080099 if (pid == None or pid >= TFM_PID_BASE) \
Kevin Peng8849b6a2021-11-09 14:17:35 +0800100 and len(service_list) == 0 and len(irq_list) == 0:
101 raise Exception('{} must declare at least either a secure service or an IRQ!'
102 .format(partition_manifest['name']))
103
104 # Service FF-M manifest validation
105 for service in service_list:
Mingyang Sun294ce2e2021-06-11 11:58:24 +0800106 if 'version' not in service.keys():
107 service['version'] = 1
108 if 'version_policy' not in service.keys():
Kevin Peng5bc82d22021-10-19 11:18:40 +0800109 service['version_policy'] = 'STRICT'
Mingyang Sun294ce2e2021-06-11 11:58:24 +0800110
Kevin Peng5bc82d22021-10-19 11:18:40 +0800111 # SID duplication check
112 if service['sid'] in sid_list:
113 raise Exception('Service ID: {} has duplications!'.format(service['sid']))
114 else:
115 sid_list.append(service['sid'])
Ruiqi Jiang71d361c2021-06-23 17:45:55 +0100116
Mingyang Sun294ce2e2021-06-11 11:58:24 +0800117 return partition_manifest
118
Kevin Peng65064c52021-10-27 17:12:17 +0800119def process_partition_manifests(manifest_lists):
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100120 """
Kevin Peng65064c52021-10-27 17:12:17 +0800121 Parse the input manifest lists, generate the data base for genereated files
Kevin Peng655f2392019-11-27 16:33:02 +0800122 and generate manifest header files.
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100123
124 Parameters
125 ----------
Kevin Peng65064c52021-10-27 17:12:17 +0800126 manifest_lists:
127 A list of Secure Partition manifest lists and their original paths.
128 The manifest lists might be processed by CMake and the paths might be
129 different to the original ones. Original paths are needed to handle
130 relative paths in the lists.
131 The format must be [list A, orignal path A, list B, orignal path B, ...]
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100132
133 Returns
134 -------
Kevin Peng5bc82d22021-10-19 11:18:40 +0800135 The manifest data base.
Edison Ai48b2d9e2019-06-24 14:39:45 +0800136 """
Kevin Peng655f2392019-11-27 16:33:02 +0800137
Kevin Peng5bc82d22021-10-19 11:18:40 +0800138 context = {}
139
Ken Liu861b0782021-05-22 13:15:08 +0800140 partition_list = []
Kevin Peng65064c52021-10-27 17:12:17 +0800141 all_manifests = []
Kevin Peng56b0ea62021-10-18 11:32:57 +0800142 pid_list = []
143 no_pid_manifest_idx = []
Xinyu Zhang90f08dc2022-01-12 15:55:17 +0800144 partition_statistics = {
Xinyu Zhang2bc4d572021-12-27 16:37:46 +0800145 'connection_based_srv_num': 0,
Xinyu Zhang90f08dc2022-01-12 15:55:17 +0800146 'ipc_partition_num': 0,
147 'sfn_partition_num': 0
148 }
Kevin Peng655f2392019-11-27 16:33:02 +0800149
Kevin Peng65064c52021-10-27 17:12:17 +0800150 # Get all the manifests information as a dictionary
151 for i, item in enumerate(manifest_lists):
152 if i % 2 == 0 and not os.path.isfile(item):
153 print('Manifest list item [{}] must be a file'.format(i))
154 exit(1)
Kevin Peng655f2392019-11-27 16:33:02 +0800155
Kevin Peng65064c52021-10-27 17:12:17 +0800156 if i % 2 == 1:
157 if not os.path.isdir(item):
158 print('Manifest list item [{}] must be a directory'.format(i))
159 exit(1)
David Hub2694202021-07-15 14:58:39 +0800160
Kevin Peng65064c52021-10-27 17:12:17 +0800161 # Skip original manifest paths
162 continue
David Hub2694202021-07-15 14:58:39 +0800163
Kevin Peng65064c52021-10-27 17:12:17 +0800164 # The manifest list file generated by configure_file()
165 with open(item) as manifest_list_yaml_file:
166 manifest_dic = yaml.safe_load(manifest_list_yaml_file)['manifest_list']
167 for dict in manifest_dic:
168 # Add original path of manifest list.
169 # The validation will be done in the next loop.
170 dict['list_path'] = manifest_lists[i + 1]
171 all_manifests.append(dict)
172
173 # Parse the manifests
174 for i, manifest_item in enumerate(all_manifests):
Kevin Peng68d9a3a2021-10-18 11:39:54 +0800175 valid_enabled_conditions = ['on', 'true', 'enabled']
Kevin Peng50f413c2021-11-12 10:31:45 +0800176 valid_disabled_conditions = ['off', 'false', 'disabled', '']
Kevin Peng68d9a3a2021-10-18 11:39:54 +0800177 is_enabled = ''
178
179 if 'conditional' in manifest_item.keys():
Kevin Peng50f413c2021-11-12 10:31:45 +0800180 is_enabled = str(manifest_item['conditional']).lower()
Kevin Peng68d9a3a2021-10-18 11:39:54 +0800181 else:
182 # Partitions without 'conditional' is alwasy on
183 is_enabled = 'on'
184
185 if is_enabled in valid_disabled_conditions:
186 continue
187 elif is_enabled not in valid_enabled_conditions:
188 raise Exception('Invalid "conditional" attribute: "{}" for {}. '
189 'Please set to one of {} or {}, case-insensitive.'\
190 .format(manifest_item['conditional'],
191 manifest_item['name'],
192 valid_enabled_conditions, valid_disabled_conditions))
193
Xinyu Zhangc46ee1f2021-04-01 10:10:43 +0800194 # Check if partition ID is manually set
195 if 'pid' not in manifest_item.keys():
196 no_pid_manifest_idx.append(i)
Kevin Peng8849b6a2021-11-09 14:17:35 +0800197 pid = None
Kevin Peng56b0ea62021-10-18 11:32:57 +0800198 else:
Kevin Peng8849b6a2021-11-09 14:17:35 +0800199 pid = manifest_item['pid']
200
201 # Check if partition ID is duplicated
202 if pid in pid_list:
203 raise Exception('PID No. {pid} has already been used!'.format(pid))
204 else:
205 pid_list.append(pid)
Xinyu Zhang19504a52021-03-31 16:26:20 +0800206
Raef Coles558487a2020-10-29 13:09:44 +0000207 # Replace environment variables in the manifest path
Kevin Peng655f2392019-11-27 16:33:02 +0800208 manifest_path = os.path.expandvars(manifest_item['manifest'])
Kevin Peng65064c52021-10-27 17:12:17 +0800209 # Convert to absolute path. If it's already abspath, the path will not be changed.
210 manifest_path = os.path.join(manifest_item['list_path'], manifest_path).replace('\\', '/')
David Hub2694202021-07-15 14:58:39 +0800211
Kevin Peng5bc82d22021-10-19 11:18:40 +0800212 with open(manifest_path) as manifest_file:
Kevin Peng8849b6a2021-11-09 14:17:35 +0800213 manifest = manifest_validation(yaml.safe_load(manifest_file), pid)
Kevin Peng655f2392019-11-27 16:33:02 +0800214
Kevin Pengce99e5d2021-11-09 18:06:53 +0800215 if pid == None or pid >= TFM_PID_BASE:
Kevin Pengd08f3ba2021-11-18 15:18:56 +0800216 # Count the number of IPC/SFN partitions
217 if manifest['psa_framework_version'] == 1.1 and manifest['model'] == 'SFN':
Xinyu Zhang90f08dc2022-01-12 15:55:17 +0800218 partition_statistics['sfn_partition_num'] += 1
Kevin Pengd08f3ba2021-11-18 15:18:56 +0800219 else:
Xinyu Zhang90f08dc2022-01-12 15:55:17 +0800220 partition_statistics['ipc_partition_num'] += 1
Mingyang Suneab7eae2021-09-30 13:06:52 +0800221
Xinyu Zhang2bc4d572021-12-27 16:37:46 +0800222 for service in manifest.get('services', []):
223 if 'connection_based' not in service.keys():
224 partition_statistics['connection_based_srv_num'] += 1
225 elif service['connection_based']:
226 partition_statistics['connection_based_srv_num'] += 1
227
Kevin Peng65064c52021-10-27 17:12:17 +0800228 manifest_out_basename = os.path.splitext(os.path.basename(manifest_path))[0]
Kevin Peng655f2392019-11-27 16:33:02 +0800229
Kevin Peng4fade072021-10-26 17:57:50 +0800230 if 'output_path' in manifest_item:
Kevin Peng4fade072021-10-26 17:57:50 +0800231 output_path = os.path.expandvars(manifest_item['output_path'])
Kevin Peng4fade072021-10-26 17:57:50 +0800232 else:
Kevin Peng65064c52021-10-27 17:12:17 +0800233 output_path = ''
David Hub2694202021-07-15 14:58:39 +0800234
Kevin Peng5bc82d22021-10-19 11:18:40 +0800235 manifest_head_file = os.path.join(OUT_DIR, output_path, 'psa_manifest',
236 '{}.h'.format(manifest_out_basename))\
237 .replace('\\', '/')
238 intermedia_file = os.path.join(OUT_DIR, output_path, 'auto_generated',
239 'intermedia_{}.c'.format(manifest_out_basename))\
240 .replace('\\', '/')
241 load_info_file = os.path.join(OUT_DIR, output_path, 'auto_generated',
242 'load_info_{}.c'.format(manifest_out_basename))\
243 .replace('\\', '/')
Kevin Peng655f2392019-11-27 16:33:02 +0800244
Kevin Peng5bc82d22021-10-19 11:18:40 +0800245 partition_list.append({'manifest': manifest, 'attr': manifest_item,
246 'manifest_out_basename': manifest_out_basename,
247 'header_file': manifest_head_file,
248 'intermedia_file': intermedia_file,
249 'loadinfo_file': load_info_file})
Ken Liu861b0782021-05-22 13:15:08 +0800250
Kevin Peng56b0ea62021-10-18 11:32:57 +0800251 # Automatically assign PIDs for partitions without 'pid' attribute
Kevin Pengce99e5d2021-11-09 18:06:53 +0800252 pid = max(pid_list, default = TFM_PID_BASE - 1)
Kevin Peng56b0ea62021-10-18 11:32:57 +0800253 for idx in no_pid_manifest_idx:
Kevin Pengc424eec2021-06-25 17:26:11 +0800254 pid += 1
Kevin Peng65064c52021-10-27 17:12:17 +0800255 all_manifests[idx]['pid'] = pid
Kevin Peng56b0ea62021-10-18 11:32:57 +0800256 pid_list.append(pid)
257
Kevin Peng5bc82d22021-10-19 11:18:40 +0800258 context['partitions'] = partition_list
Xinyu Zhang90f08dc2022-01-12 15:55:17 +0800259 context['partition_statistics'] = partition_statistics
Kevin Pengce99e5d2021-11-09 18:06:53 +0800260 context['stateless_services'] = process_stateless_services(partition_list)
Ruiqi Jiang71d361c2021-06-23 17:45:55 +0100261
Kevin Peng5bc82d22021-10-19 11:18:40 +0800262 return context
Ken Liu861b0782021-05-22 13:15:08 +0800263
264def gen_per_partition_files(context):
265 """
266 Generate per-partition files
267
268 Parameters
269 ----------
270 context:
271 context contains partition infos
272 """
273
Kevin Peng5bc82d22021-10-19 11:18:40 +0800274 partition_context = {}
Sherry Zhangf58f2bd2022-01-10 17:21:11 +0800275 partition_context['utilities'] = context['utilities']
Ken Liu861b0782021-05-22 13:15:08 +0800276
Kevin Peng5bc82d22021-10-19 11:18:40 +0800277 manifesttemplate = ENV.get_template(os.path.join(sys.path[0], 'templates/manifestfilename.template'))
278 memorytemplate = ENV.get_template(os.path.join(sys.path[0], 'templates/partition_intermedia.template'))
279 infotemplate = ENV.get_template(os.path.join(sys.path[0], 'templates/partition_load_info.template'))
Ken Liu861b0782021-05-22 13:15:08 +0800280
Kevin Peng5bc82d22021-10-19 11:18:40 +0800281 print ('Start to generate partition files:')
Ken Liu861b0782021-05-22 13:15:08 +0800282
283 for one_partition in context['partitions']:
Kevin Peng5bc82d22021-10-19 11:18:40 +0800284 partition_context['manifest'] = one_partition['manifest']
285 partition_context['attr'] = one_partition['attr']
286 partition_context['manifest_out_basename'] = one_partition['manifest_out_basename']
Ken Liu861b0782021-05-22 13:15:08 +0800287
Kevin Peng5bc82d22021-10-19 11:18:40 +0800288 print ('Generating Header: ' + one_partition['header_file'])
Ken Liu861b0782021-05-22 13:15:08 +0800289 outfile_path = os.path.dirname(one_partition['header_file'])
Kevin Peng655f2392019-11-27 16:33:02 +0800290 if not os.path.exists(outfile_path):
291 os.makedirs(outfile_path)
292
Kevin Peng5bc82d22021-10-19 11:18:40 +0800293 headerfile = io.open(one_partition['header_file'], 'w', newline=None)
294 headerfile.write(manifesttemplate.render(partition_context))
Ken Liu861b0782021-05-22 13:15:08 +0800295 headerfile.close()
Kevin Peng655f2392019-11-27 16:33:02 +0800296
Kevin Peng5bc82d22021-10-19 11:18:40 +0800297 print ('Generating Intermedia: ' + one_partition['intermedia_file'])
Ken Liu861b0782021-05-22 13:15:08 +0800298 intermediafile_path = os.path.dirname(one_partition['intermedia_file'])
Mingyang Sund20999f2020-10-15 14:53:12 +0800299 if not os.path.exists(intermediafile_path):
300 os.makedirs(intermediafile_path)
Kevin Peng5bc82d22021-10-19 11:18:40 +0800301 intermediafile = io.open(one_partition['intermedia_file'], 'w', newline=None)
302 intermediafile.write(memorytemplate.render(partition_context))
Ken Liu861b0782021-05-22 13:15:08 +0800303 intermediafile.close()
Mingyang Sund20999f2020-10-15 14:53:12 +0800304
Kevin Peng5bc82d22021-10-19 11:18:40 +0800305 print ('Generating Loadinfo: ' + one_partition['loadinfo_file'])
Ken Liu861b0782021-05-22 13:15:08 +0800306 infofile_path = os.path.dirname(one_partition['loadinfo_file'])
Mingyang Sunf6a78572021-04-02 16:51:05 +0800307 if not os.path.exists(infofile_path):
308 os.makedirs(infofile_path)
Kevin Peng5bc82d22021-10-19 11:18:40 +0800309 infooutfile = io.open(one_partition['loadinfo_file'], 'w', newline=None)
310 infooutfile.write(infotemplate.render(partition_context))
Ken Liu861b0782021-05-22 13:15:08 +0800311 infooutfile.close()
Mingyang Sunf6a78572021-04-02 16:51:05 +0800312
Kevin Peng5bc82d22021-10-19 11:18:40 +0800313 print ('Per-partition files done:')
Mingyang Sunf6a78572021-04-02 16:51:05 +0800314
Ken Liu861b0782021-05-22 13:15:08 +0800315def gen_summary_files(context, gen_file_lists):
Kevin Peng655f2392019-11-27 16:33:02 +0800316 """
317 Generate files according to the gen_file_list
Edison Ai48b2d9e2019-06-24 14:39:45 +0800318
319 Parameters
320 ----------
Raef Colesf42f0882020-07-10 10:01:58 +0100321 gen_file_lists:
322 The lists of files to generate
Edison Ai48b2d9e2019-06-24 14:39:45 +0800323 """
Kevin Peng655f2392019-11-27 16:33:02 +0800324 file_list = []
Shawn Shana9ad1e02019-08-07 15:49:48 +0800325
Raef Colesf42f0882020-07-10 10:01:58 +0100326 for f in gen_file_lists:
327 with open(f) as file_list_yaml_file:
Kevin Peng655f2392019-11-27 16:33:02 +0800328 file_list_yaml = yaml.safe_load(file_list_yaml_file)
Kevin Peng5bc82d22021-10-19 11:18:40 +0800329 file_list.extend(file_list_yaml['file_list'])
Edison Ai48b2d9e2019-06-24 14:39:45 +0800330
Kevin Peng5bc82d22021-10-19 11:18:40 +0800331 print('Start to generate file from the generated list:')
Kevin Peng655f2392019-11-27 16:33:02 +0800332 for file in file_list:
Raef Coles558487a2020-10-29 13:09:44 +0000333 # Replace environment variables in the output filepath
Kevin Peng5bc82d22021-10-19 11:18:40 +0800334 manifest_out_file = os.path.expandvars(file['output'])
Raef Coles558487a2020-10-29 13:09:44 +0000335 # Replace environment variables in the template filepath
Kevin Peng5bc82d22021-10-19 11:18:40 +0800336 templatefile_name = os.path.expandvars(file['template'])
Edison Ai48b2d9e2019-06-24 14:39:45 +0800337
Kevin Peng4fade072021-10-26 17:57:50 +0800338 manifest_out_file = os.path.join(OUT_DIR, manifest_out_file)
Edison Ai48b2d9e2019-06-24 14:39:45 +0800339
Kevin Peng5bc82d22021-10-19 11:18:40 +0800340 print ('Generating ' + manifest_out_file)
Ken Liu861b0782021-05-22 13:15:08 +0800341 outfile_path = os.path.dirname(manifest_out_file)
Kevin Peng655f2392019-11-27 16:33:02 +0800342 if not os.path.exists(outfile_path):
343 os.makedirs(outfile_path)
Edison Ai48b2d9e2019-06-24 14:39:45 +0800344
Kevin Peng655f2392019-11-27 16:33:02 +0800345 template = ENV.get_template(templatefile_name)
Edison Ai6e3f2a32019-06-11 15:29:05 +0800346
Kevin Peng5bc82d22021-10-19 11:18:40 +0800347 outfile = io.open(manifest_out_file, 'w', newline=None)
Kevin Peng655f2392019-11-27 16:33:02 +0800348 outfile.write(template.render(context))
349 outfile.close()
Edison Ai48b2d9e2019-06-24 14:39:45 +0800350
Kevin Peng5bc82d22021-10-19 11:18:40 +0800351 print ('Generation of files done')
Edison Ai48b2d9e2019-06-24 14:39:45 +0800352
Kevin Pengce99e5d2021-11-09 18:06:53 +0800353def process_stateless_services(partitions):
Mingyang Suna1ca6112021-01-11 11:34:59 +0800354 """
355 This function collects all stateless services together, and allocates
Mingyang Sun4ecea992021-03-30 17:56:26 +0800356 stateless handles for them.
Kevin Pengc05319d2021-04-22 22:59:35 +0800357 Valid stateless handle in service will be converted to an index. If the
358 stateless handle is set as "auto", or not set, framework will allocate a
359 valid index for the service.
360 Framework puts each service into a reordered stateless service list at
361 position of "index". Other unused positions are left None.
Mingyang Suna1ca6112021-01-11 11:34:59 +0800362 """
Kevin Pengce99e5d2021-11-09 18:06:53 +0800363
364 STATIC_HANDLE_CONFIG_FILE = 'secure_fw/spm/cmsis_psa/spm_ipc.h'
365
Kevin Pengc05319d2021-04-22 22:59:35 +0800366 collected_stateless_services = []
Kevin Pengce99e5d2021-11-09 18:06:53 +0800367 stateless_index_max_num = \
368 int(get_single_macro_def_from_file(STATIC_HANDLE_CONFIG_FILE, 'STATIC_HANDLE_NUM_LIMIT'), base = 10)
Mingyang Suna1ca6112021-01-11 11:34:59 +0800369
370 # Collect all stateless services first.
371 for partition in partitions:
372 # Skip the FF-M 1.0 partitions
373 if partition['manifest']['psa_framework_version'] < 1.1:
374 continue
Kevin Peng8849b6a2021-11-09 14:17:35 +0800375
376 service_list = partition['manifest'].get('services', [])
377
378 for service in service_list:
Mingyang Suna1ca6112021-01-11 11:34:59 +0800379 if 'connection_based' not in service:
380 raise Exception("'connection_based' is mandatory in FF-M 1.1 service!")
381 if service['connection_based'] is False:
Kevin Pengc05319d2021-04-22 22:59:35 +0800382 collected_stateless_services.append(service)
Mingyang Suna1ca6112021-01-11 11:34:59 +0800383
Kevin Pengc05319d2021-04-22 22:59:35 +0800384 if len(collected_stateless_services) == 0:
Mingyang Suna1ca6112021-01-11 11:34:59 +0800385 return []
386
Ken Liu861b0782021-05-22 13:15:08 +0800387 if len(collected_stateless_services) > stateless_index_max_num:
Kevin Peng5bc82d22021-10-19 11:18:40 +0800388 raise Exception('Stateless service numbers range exceed {number}.'.format(number=stateless_index_max_num))
Mingyang Suna1ca6112021-01-11 11:34:59 +0800389
390 """
Kevin Pengc05319d2021-04-22 22:59:35 +0800391 Allocate an empty stateless service list to store services.
392 Use "handle - 1" as the index for service, since handle value starts from
393 1 and list index starts from 0.
Mingyang Suna1ca6112021-01-11 11:34:59 +0800394 """
Ken Liu861b0782021-05-22 13:15:08 +0800395 reordered_stateless_services = [None] * stateless_index_max_num
Kevin Pengc05319d2021-04-22 22:59:35 +0800396 auto_alloc_services = []
Mingyang Suna1ca6112021-01-11 11:34:59 +0800397
Kevin Pengc05319d2021-04-22 22:59:35 +0800398 for service in collected_stateless_services:
399 # If not set, it is "auto" by default
400 if 'stateless_handle' not in service:
401 auto_alloc_services.append(service)
402 continue
403
Mingyang Sun4ecea992021-03-30 17:56:26 +0800404 service_handle = service['stateless_handle']
Mingyang Suna1ca6112021-01-11 11:34:59 +0800405
Mingyang Sun4ecea992021-03-30 17:56:26 +0800406 # Fill in service list with specified stateless handle, otherwise skip
407 if isinstance(service_handle, int):
Ken Liu861b0782021-05-22 13:15:08 +0800408 if service_handle < 1 or service_handle > stateless_index_max_num:
Kevin Peng5bc82d22021-10-19 11:18:40 +0800409 raise Exception('Invalid stateless_handle setting: {handle}.'.format(handle=service['stateless_handle']))
Mingyang Sun4ecea992021-03-30 17:56:26 +0800410 # Convert handle index to reordered service list index
411 service_handle = service_handle - 1
412
413 if reordered_stateless_services[service_handle] is not None:
Kevin Peng5bc82d22021-10-19 11:18:40 +0800414 raise Exception('Duplicated stateless_handle setting: {handle}.'.format(handle=service['stateless_handle']))
Mingyang Sun4ecea992021-03-30 17:56:26 +0800415 reordered_stateless_services[service_handle] = service
Kevin Pengc05319d2021-04-22 22:59:35 +0800416 elif service_handle == 'auto':
417 auto_alloc_services.append(service)
418 else:
Kevin Peng5bc82d22021-10-19 11:18:40 +0800419 raise Exception('Invalid stateless_handle setting: {handle}.'.format(handle=service['stateless_handle']))
Mingyang Sun4ecea992021-03-30 17:56:26 +0800420
Kevin Pengce99e5d2021-11-09 18:06:53 +0800421 STATIC_HANDLE_IDX_BIT_WIDTH = \
422 int(get_single_macro_def_from_file(STATIC_HANDLE_CONFIG_FILE, 'STATIC_HANDLE_IDX_BIT_WIDTH'), base = 10)
423 STATIC_HANDLE_IDX_MASK = (1 << STATIC_HANDLE_IDX_BIT_WIDTH) - 1
424
425 STATIC_HANDLE_INDICATOR_OFFSET = \
426 int(get_single_macro_def_from_file(STATIC_HANDLE_CONFIG_FILE, 'STATIC_HANDLE_INDICATOR_OFFSET'), base = 10)
427
428 STATIC_HANDLE_VER_OFFSET = \
429 int(get_single_macro_def_from_file(STATIC_HANDLE_CONFIG_FILE, 'STATIC_HANDLE_VER_OFFSET'), base = 10)
430
431 STATIC_HANDLE_VER_BIT_WIDTH = \
432 int(get_single_macro_def_from_file(STATIC_HANDLE_CONFIG_FILE, 'STATIC_HANDLE_VER_BIT_WIDTH'), base = 10)
433 STATIC_HANDLE_VER_MASK = (1 << STATIC_HANDLE_VER_BIT_WIDTH) - 1
434
Mingyang Sun4ecea992021-03-30 17:56:26 +0800435 # Auto-allocate stateless handle and encode the stateless handle
Ken Liu861b0782021-05-22 13:15:08 +0800436 for i in range(0, stateless_index_max_num):
Mingyang Sun4ecea992021-03-30 17:56:26 +0800437 service = reordered_stateless_services[i]
438
Kevin Pengc05319d2021-04-22 22:59:35 +0800439 if service == None and len(auto_alloc_services) > 0:
440 service = auto_alloc_services.pop(0)
Mingyang Sun4ecea992021-03-30 17:56:26 +0800441
Mingyang Sun453ad402021-03-17 17:58:33 +0800442 """
443 Encode stateless flag and version into stateless handle
Kevin Pengce99e5d2021-11-09 18:06:53 +0800444 Check STATIC_HANDLE_CONFIG_FILE for details
Mingyang Sun453ad402021-03-17 17:58:33 +0800445 """
Mingyang Sun4ecea992021-03-30 17:56:26 +0800446 stateless_handle_value = 0
447 if service != None:
Kevin Pengce99e5d2021-11-09 18:06:53 +0800448 stateless_index = (i & STATIC_HANDLE_IDX_MASK)
Mingyang Sun4ecea992021-03-30 17:56:26 +0800449 stateless_handle_value |= stateless_index
Kevin Pengce99e5d2021-11-09 18:06:53 +0800450 stateless_handle_value |= (1 << STATIC_HANDLE_INDICATOR_OFFSET)
451 stateless_version = (service['version'] & STATIC_HANDLE_VER_MASK) << STATIC_HANDLE_VER_OFFSET
Mingyang Sun453ad402021-03-17 17:58:33 +0800452 stateless_handle_value |= stateless_version
Mingyang Sun4ecea992021-03-30 17:56:26 +0800453 service['stateless_handle_value'] = '0x{0:08x}'.format(stateless_handle_value)
Ken Liu861b0782021-05-22 13:15:08 +0800454 service['stateless_handle_index'] = stateless_index
Mingyang Suna1ca6112021-01-11 11:34:59 +0800455
Mingyang Sun4ecea992021-03-30 17:56:26 +0800456 reordered_stateless_services[i] = service
457
458 return reordered_stateless_services
Mingyang Suna1ca6112021-01-11 11:34:59 +0800459
Kevin Peng655f2392019-11-27 16:33:02 +0800460def parse_args():
Raef Coles558487a2020-10-29 13:09:44 +0000461 parser = argparse.ArgumentParser(description='Parse secure partition manifest list and generate files listed by the file list',
462 epilog='Note that environment variables in template files will be replaced with their values')
463
Kevin Peng655f2392019-11-27 16:33:02 +0800464 parser.add_argument('-o', '--outdir'
465 , dest='outdir'
Kevin Peng4fade072021-10-26 17:57:50 +0800466 , required=True
Kevin Peng655f2392019-11-27 16:33:02 +0800467 , metavar='out_dir'
Kevin Peng4fade072021-10-26 17:57:50 +0800468 , help='The root directory for generated files')
Shawn Shana9ad1e02019-08-07 15:49:48 +0800469
Kevin Peng5bc82d22021-10-19 11:18:40 +0800470 parser.add_argument('-m', '--manifest-lists'
Raef Colesf42f0882020-07-10 10:01:58 +0100471 , nargs='+'
Kevin Peng5bc82d22021-10-19 11:18:40 +0800472 , dest='manifest_lists'
Raef Colesf42f0882020-07-10 10:01:58 +0100473 , required=True
Kevin Peng65064c52021-10-27 17:12:17 +0800474 , metavar='manifest list'
475 , help='A list of Secure Partition manifest lists and their original paths.\n\
476 The manifest lists might be processed by CMake and\n\
477 the path might be different to the original one\n\
478 The format must be [list A, orignal path A, list B, orignal path B, ...]')
Kevin Peng655f2392019-11-27 16:33:02 +0800479
480 parser.add_argument('-f', '--file-list'
Raef Colesf42f0882020-07-10 10:01:58 +0100481 , nargs='+'
Kevin Peng655f2392019-11-27 16:33:02 +0800482 , dest='gen_file_args'
Raef Colesf42f0882020-07-10 10:01:58 +0100483 , required=True
Kevin Peng655f2392019-11-27 16:33:02 +0800484 , metavar='file-list'
Raef Colesf42f0882020-07-10 10:01:58 +0100485 , help='These files descripe the file list to generate')
Kevin Peng655f2392019-11-27 16:33:02 +0800486
487 args = parser.parse_args()
Kevin Peng655f2392019-11-27 16:33:02 +0800488
Kevin Peng65064c52021-10-27 17:12:17 +0800489 if len(args.manifest_lists) % 2 != 0:
490 print('Invalid structure in manifest lists.\n'
491 'Each element shall consist of a manifest list and its original path')
492 exit(1)
493
Kevin Peng655f2392019-11-27 16:33:02 +0800494 return args
495
496ENV = Environment(
497 loader = TemplateLoader(),
498 autoescape = select_autoescape(['html', 'xml']),
499 lstrip_blocks = True,
500 trim_blocks = True,
501 keep_trailing_newline = True
502 )
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100503
Miklos Balint470919c2018-05-22 17:51:29 +0200504def main():
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100505 """
506 The entry point of the script.
507
508 Generates the output files based on the templates and the manifests.
509 """
Shawn Shana9ad1e02019-08-07 15:49:48 +0800510
Kevin Peng655f2392019-11-27 16:33:02 +0800511 global OUT_DIR
Shawn Shana9ad1e02019-08-07 15:49:48 +0800512
Kevin Peng655f2392019-11-27 16:33:02 +0800513 args = parse_args()
Shawn Shana9ad1e02019-08-07 15:49:48 +0800514
Kevin Peng5bc82d22021-10-19 11:18:40 +0800515 OUT_DIR = os.path.abspath(args.outdir)
Kevin Peng655f2392019-11-27 16:33:02 +0800516
Kevin Peng5bc82d22021-10-19 11:18:40 +0800517 manifest_lists = [os.path.abspath(x) for x in args.manifest_lists]
518 gen_file_lists = [os.path.abspath(x) for x in args.gen_file_args]
Shawn Shana9ad1e02019-08-07 15:49:48 +0800519
Shawn Shana9ad1e02019-08-07 15:49:48 +0800520 """
Kevin Peng655f2392019-11-27 16:33:02 +0800521 Relative path to TF-M root folder is supported in the manifests
522 and default value of manifest list and generated file list are relative to TF-M root folder as well,
523 so first change directory to TF-M root folder.
Shawn Shana9ad1e02019-08-07 15:49:48 +0800524 By doing this, the script can be executed anywhere
Kevin Peng655f2392019-11-27 16:33:02 +0800525 The script is located in <TF-M root folder>/tools, so sys.path[0]<location of the script>/.. is TF-M root folder.
Shawn Shana9ad1e02019-08-07 15:49:48 +0800526 """
Kevin Peng5bc82d22021-10-19 11:18:40 +0800527 os.chdir(os.path.join(sys.path[0], '..'))
Shawn Shana9ad1e02019-08-07 15:49:48 +0800528
Kevin Peng65064c52021-10-27 17:12:17 +0800529 context = process_partition_manifests(manifest_lists)
Mate Toth-Pal36f21842018-11-08 16:12:51 +0100530
Edison Ai6e3f2a32019-06-11 15:29:05 +0800531 utilities = {}
Mingyang Suna1ca6112021-01-11 11:34:59 +0800532 utilities['donotedit_warning'] = donotedit_warning
Miklos Balint470919c2018-05-22 17:51:29 +0200533
Kevin Peng655f2392019-11-27 16:33:02 +0800534 context['utilities'] = utilities
Mingyang Suneab7eae2021-09-30 13:06:52 +0800535
Ken Liu861b0782021-05-22 13:15:08 +0800536 gen_per_partition_files(context)
Kevin Peng5bc82d22021-10-19 11:18:40 +0800537 gen_summary_files(context, gen_file_lists)
Miklos Balint470919c2018-05-22 17:51:29 +0200538
Kevin Peng5bc82d22021-10-19 11:18:40 +0800539if __name__ == '__main__':
Miklos Balint470919c2018-05-22 17:51:29 +0200540 main()