blob: 93666255a3343c90b08d392e99bb4ca26fc99892 [file] [log] [blame]
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +01001#!/usr/bin/env python3
2# Copyright lowRISC contributors.
3# Licensed under the Apache License, Version 2.0, see LICENSE for details.
4# SPDX-License-Identifier: Apache-2.0
Sam Elliott1052ce12020-10-14 15:21:12 +01005"""
6This script generates various descriptions of the ROM_EXT manifest format based
7on the `sw/device/rom_exts/manifest.hjson` machine-readable description of that
8format.
9
10The main part of `mainfest.hjson` is a list of fields described using a list of
11dicts. These features are given in sequential order.
12
13Each dict can describe one of the following kinds of data format features:
14- `type: reserved` which is a reserved area of a certain size. These definitions
15 are not named, and definitions are not produced for them.
16- `type: field` which is a readable field of a certain size. We generate
17 definitions for the start offset of the field, and for the field size (in both
18 bytes and words). These must have a name.
19- `type: offset` which is a named offset into the ROM_EXT image. This implicitly
20 has a size of zero, but no size definitions are given for these fields.
21 Offsets with an alignment can move any features that follow them. These must
22 have a name.
23
24All data format features have a default alignment of 32-bits. This alignment can
25be reduced or expanded with the `alignment` key.
26
27All sizes and alignments are given in *bits*, not bytes.
28
29All fields and offsets must have a name, and optionally a description in the
30`desc` key.
31
32The generator currently produces the following files (into the given output
33directory):
34- `template.h`, from `sw/device/rom_exts/manifest.h.tpl` which provides field
35 size and offset preprocessor definitions for use from C.
36"""
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010037
38import argparse
Sam Elliott3c740b32020-11-25 10:07:32 +000039import subprocess
Sam Elliott3459b7e2020-11-27 16:36:27 +000040from pathlib import Path
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010041
42import hjson
43from mako.template import Template
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010044from topgen.c import MemoryRegion, Name
45
46DESC = """ROM_EXT manifest generator"""
47
48USAGE = """
49 rom-ext-manifest-generator --input-dir:
50 Directory where manifest.hjson and manifest.h.tpl reside.
51
52 rom-ext-manifest-generator --output-dir:
Sam Elliottdd088bc2020-10-14 09:19:15 +010053 Directory where manifest.h will be created.
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +000054
Sam Elliott3c740b32020-11-25 10:07:32 +000055 rom-ext-manifest-generator --output-files=[all | c | rust | format]:
56 Type of files to be generated:
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +000057
Sam Elliott3c740b32020-11-25 10:07:32 +000058 all - All files listed below
59 c - C header file
60 rust - Rust module file
61 format - Format description file (plaintext)
Sam Elliott3459b7e2020-11-27 16:36:27 +000062
63 rom-ext-manifest-generator --verbose:
64 Print extra information including resulting field offsets and alignment.
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010065"""
66
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +000067
Sam Elliott1052ce12020-10-14 15:21:12 +010068class MemoryOffset(object):
69 def __init__(self, name, offset):
70 self.name = name
71 self.offset = offset
72
73 def offset_name(self):
74 return self.name + Name(["offset"])
75
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010076
Sam Elliott3459b7e2020-11-27 16:36:27 +000077def generate_defines(fields, verbose=False):
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +000078 """ Generates manifest defines.
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010079
Sam Elliott3c740b32020-11-25 10:07:32 +000080 This produces two lists of tuples. One with a field name and the
81 `MemoryRegion` object, and one with `MemoryOffset` object. Please see the
82 description at the top for more information on the differences between these
83 objects.
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010084 """
Sam Elliott3459b7e2020-11-27 16:36:27 +000085 def print_field_info(name, offset, size, alignment, required_alignment):
86 if verbose:
87 print("0x{:04x} - 0x{:04x}: {} (alignment: {} reqd: {})".format(
88 offset, offset + size, name, alignment, required_alignment))
89
90 def print_offset_info(name, offset, alignment, required_alignment):
91 if verbose:
92 print(" @ 0x{:04x}: {} (alignment: {} reqd: {})".format(
93 offset, name, alignment, required_alignment))
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010094
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +010095 base_name = Name.from_snake_case("ROM_EXT")
96
Sam Elliott1052ce12020-10-14 15:21:12 +010097 regions = []
98 offsets = []
99 current_offset_bytes = 0
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100100 for field in fields:
Sam Elliott1052ce12020-10-14 15:21:12 +0100101 required_alignment_bits = field.get("alignment", 32)
102 assert required_alignment_bits % 8 == 0
103 required_alignment_bytes = required_alignment_bits // 8
104
105 # The 8-byte two-step https://zinascii.com/2014/the-8-byte-two-step.html
Sam Elliott3459b7e2020-11-27 16:36:27 +0000106 # This ends up aligning `new_offset_bytes` to `required_alignment_bytes`
Sam Elliott1052ce12020-10-14 15:21:12 +0100107 # that is greater than or equal to `current_offset_bytes`.
Sam Elliott3459b7e2020-11-27 16:36:27 +0000108 new_offset_bytes = (current_offset_bytes + required_alignment_bytes - 1) \
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000109 & ~(required_alignment_bytes - 1)
Sam Elliott1052ce12020-10-14 15:21:12 +0100110
Sam Elliott3459b7e2020-11-27 16:36:27 +0000111 if new_offset_bytes != current_offset_bytes and verbose:
112 print("0x{:04x} - 0x{:04x}: - (realignment) -".format(
113 current_offset_bytes, new_offset_bytes))
114
115 current_offset_bytes = new_offset_bytes
116 # This works becuase e.g. 6 is `0b0...00110` and ~(6-1) is `0b1..11010`,
117 # giving a result of `0b0...010`, or 2.
118 current_offset_alignment = current_offset_bytes \
119 & ~(current_offset_bytes - 1)
120
Sam Elliott1052ce12020-10-14 15:21:12 +0100121 if field['type'] == "offset":
122 offset_name = base_name + Name.from_snake_case(field['name'])
123 offset = MemoryOffset(offset_name, current_offset_bytes)
124 offsets.append((field['name'], offset))
125
Sam Elliott3459b7e2020-11-27 16:36:27 +0000126 print_offset_info(field['name'], current_offset_bytes,
127 current_offset_alignment,
128 required_alignment_bytes)
129
Sam Elliott1052ce12020-10-14 15:21:12 +0100130 else:
131 assert field['size'] % 8 == 0
132 size_bytes = field['size'] // 8
133 if field['type'] == "field":
134 region_name = base_name + Name.from_snake_case(field['name'])
Sam Elliott3459b7e2020-11-27 16:36:27 +0000135 region = MemoryRegion(region_name, current_offset_bytes,
136 size_bytes)
Sam Elliott1052ce12020-10-14 15:21:12 +0100137 regions.append((field['name'], region))
Sam Elliott3459b7e2020-11-27 16:36:27 +0000138
139 print_field_info(field['name'], current_offset_bytes,
140 size_bytes, current_offset_alignment,
141 required_alignment_bytes)
142 elif field['type'] == 'reserved' and verbose:
143 print_field_info('- reserved -', current_offset_bytes,
144 size_bytes, current_offset_alignment, 0)
145
Sam Elliott1052ce12020-10-14 15:21:12 +0100146 current_offset_bytes += size_bytes
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100147
Sam Elliott3c740b32020-11-25 10:07:32 +0000148 return (regions, offsets)
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000149
150
Sam Elliott3c740b32020-11-25 10:07:32 +0000151def generate_cheader(regions, offsets, input_dir, output_dir):
152 """Generates C header file.
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000153
Sam Elliott3c740b32020-11-25 10:07:32 +0000154 This uses the lists of `MemoryRegion` and `MemoryOffset` objects, to
155 generate a C header, using a template and placing the output into
156 `output_dir`.
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000157 """
158
159 template_path = input_dir / 'manifest.h.tpl'
160 output_path = output_dir / 'manifest.h'
161
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000162 with template_path.open('r') as f:
163 template = Template(f.read())
164
165 header = template.render(regions=regions, offsets=offsets)
166
167 with output_path.open('w') as f:
168 f.write(header)
169
Sam Elliott3c740b32020-11-25 10:07:32 +0000170 print('C header sucessfuly written to {}.'.format(output_path))
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000171
172
Sam Elliott3c740b32020-11-25 10:07:32 +0000173def generate_rust_header(regions, offsets, input_dir, output_dir):
174 """Generates Rust module.
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000175
Sam Elliott3c740b32020-11-25 10:07:32 +0000176 This uses the lists of `MemoryRegion` and `MemoryOffset` objects, to
177 generate a Rust module, using a template and placing the output into
178 `output_dir`.
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000179 """
180
181 template_path = input_dir / 'manifest.rs.tpl'
182 output_path = output_dir / 'manifest.rs'
183
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100184 with template_path.open('r') as f:
185 template = Template(f.read())
186
Sam Elliott1052ce12020-10-14 15:21:12 +0100187 header = template.render(regions=regions, offsets=offsets)
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100188
189 with output_path.open('w') as f:
190 f.write(header)
191
Sam Elliott3c740b32020-11-25 10:07:32 +0000192 print('Rust module sucessfuly written to {}.'.format(output_path))
193
194
195def generate_format_description(regions, output_dir):
196 """Generates Plaintext Format Description.
197
198 This uses the `MemoryRegion` objects to generate a format description using
199 the `protocol` tool [1]. This produces an ascii diagram of how the fields of
200 a format are laid out.
201
202 [1]: https://github.com/luismartingarcia/protocol
203 """
204
205 output_path = output_dir / 'manifest.txt'
206
Sam Elliott3459b7e2020-11-27 16:36:27 +0000207 truncate_length = 16 # bytes
Sam Elliott3c740b32020-11-25 10:07:32 +0000208 bits_in_byte = 8
209
210 verbose_regions = []
Sam Elliott3459b7e2020-11-27 16:36:27 +0000211 current_offset = 0 # bytes
Sam Elliott3c740b32020-11-25 10:07:32 +0000212
213 truncation_lines = []
Sam Elliott3459b7e2020-11-27 16:36:27 +0000214 current_truncation_delta = 0 # bytes
Sam Elliott3c740b32020-11-25 10:07:32 +0000215
216 # We need to re-process this info to re-add reserved regions of the right
217 # size, and also to truncate really long fields.
218 for name, mem_region in regions:
219 new_offset = mem_region.base_addr
220 assert new_offset >= current_offset
221
222 # Pad with a reserved field to get to new offset
223 if new_offset != current_offset:
Sam Elliott3459b7e2020-11-27 16:36:27 +0000224 verbose_regions.append("- reserved -:{}".format(
225 (new_offset - current_offset) * bits_in_byte))
Sam Elliott3c740b32020-11-25 10:07:32 +0000226
227 current_offset = new_offset
228
229 # Add a (potentially truncated) field
230 if mem_region.size_bytes > truncate_length:
231 # We only allow truncated regions at 4-byte offsets.
Sam Elliott3459b7e2020-11-27 16:36:27 +0000232 assert (current_offset % 4 == 0)
233 verbose_regions.append("{} ({} bits):{}".format(
234 name, mem_region.size_bytes * bits_in_byte,
235 truncate_length * bits_in_byte))
Sam Elliott3c740b32020-11-25 10:07:32 +0000236
237 # Save some information so we know where to insert the `~~ break ~~` line.
238 data_line = (current_offset - current_truncation_delta) // 4
239 truncation_lines.append(data_line)
240 current_truncation_delta += mem_region.size_bytes - truncate_length
241
242 else:
Sam Elliott3459b7e2020-11-27 16:36:27 +0000243 verbose_regions.append("{}:{}".format(
244 name, mem_region.size_bytes * bits_in_byte))
Sam Elliott3c740b32020-11-25 10:07:32 +0000245
246 current_offset = new_offset + mem_region.size_bytes
247
248 # Add a field for the image itself:
Sam Elliott3459b7e2020-11-27 16:36:27 +0000249 verbose_regions.append("code image:{}".format(truncate_length *
250 bits_in_byte))
Sam Elliott3c740b32020-11-25 10:07:32 +0000251 truncation_lines.append((current_offset - current_truncation_delta) // 4)
252
253 protocol_input = ",".join(verbose_regions)
Sam Elliott3459b7e2020-11-27 16:36:27 +0000254 protocol_result = subprocess.run(
255 ["protocol", "--bits", "32", protocol_input],
256 universal_newlines=True,
257 capture_output=True)
Sam Elliott3c740b32020-11-25 10:07:32 +0000258 protocol_output = protocol_result.stdout
259
260 truncation_mark = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ break ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
261 # The formula here depends on the output of `protocol`. The idea is to
262 # replace a line *after* the label with `truncation_mark`, preferrably a
263 # line that otherwise would denote the space between adjacent words.
264 visual_truncations = [line * 2 + 8 for line in truncation_lines]
265
266 with output_path.open('w') as f:
267 for idx, line in enumerate(protocol_output.splitlines(keepends=True)):
268 if idx in visual_truncations:
269 f.write(truncation_mark)
270 else:
271 f.write(line)
272
273 print('Format description successfully written to {}.'.format(output_path))
274
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100275
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100276def main():
Sam Elliott3c740b32020-11-25 10:07:32 +0000277 ALL_PARTS = ["c", "rust", "format"]
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000278
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100279 parser = argparse.ArgumentParser(
280 formatter_class=argparse.RawDescriptionHelpFormatter,
281 usage=USAGE,
282 description=DESC)
283
Sam Elliott3459b7e2020-11-27 16:36:27 +0000284 parser.add_argument('-v',
285 '--verbose',
286 action='store_true',
287 default=False,
288 help='Print Extra Information.')
289
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100290 parser.add_argument('--input-dir',
291 required=True,
292 type=Path,
293 help='Manifest hjson and template directory.')
294
295 parser.add_argument('--output-dir',
296 required=True,
297 type=Path,
Sam Elliott3c740b32020-11-25 10:07:32 +0000298 help='Manifest file output directory.')
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100299
Sam Elliott3c740b32020-11-25 10:07:32 +0000300 parser.add_argument('--output-files',
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000301 choices=['all'] + ALL_PARTS,
302 default=[],
303 action='append',
Sam Elliott3c740b32020-11-25 10:07:32 +0000304 help='The type of files to be produced.')
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000305
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100306 args = parser.parse_args()
307
308 manifest_hjson_file = args.input_dir / 'manifest.hjson'
309
310 with manifest_hjson_file.open('r') as hjson_file:
311 obj = hjson.loads(hjson_file.read())
312
Sam Elliott3c740b32020-11-25 10:07:32 +0000313 if len(args.output_files) == 0:
314 args.output_files += ['all']
315 if 'all' in args.output_files:
316 args.output_files += ALL_PARTS
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000317
Sam Elliott3459b7e2020-11-27 16:36:27 +0000318 regions, offsets = generate_defines(obj['fields'], args.verbose)
Silvestrs Timofejevs522a6082020-11-11 11:33:28 +0000319
Sam Elliott3c740b32020-11-25 10:07:32 +0000320 if "c" in args.output_files:
321 generate_cheader(regions, offsets, args.input_dir, args.output_dir)
322
323 if "rust" in args.output_files:
324 generate_rust_header(regions, offsets, args.input_dir, args.output_dir)
325
326 if "format" in args.output_files:
327 generate_format_description(regions, args.output_dir)
Silvestrs Timofejevs4a6073e2020-09-24 10:00:19 +0100328
329
330if __name__ == '__main__':
331 main()