blob: df337bc3bf60cabdbbc31638a4c694b51076ea30 [file] [log] [blame]
David Burger7fd1dbe2020-03-26 09:26:55 -06001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Transforms config from /config/proto/api proto format to platform JSON."""
7
8import argparse
9import json
10import pprint
C Shapiro90fda252020-04-17 14:34:57 -050011import os
David Burger7fd1dbe2020-03-26 09:26:55 -060012import sys
C Shapiro90fda252020-04-17 14:34:57 -050013import re
David Burger7fd1dbe2020-03-26 09:26:55 -060014
15from collections import namedtuple
16
Prathmesh Prabhu72f8a002020-04-10 09:57:53 -070017from chromiumos.config.payload import config_bundle_pb2
18from chromiumos.config.api import device_brand_pb2
19from chromiumos.config.api.software import brand_config_pb2
David Burger7fd1dbe2020-03-26 09:26:55 -060020
21Config = namedtuple('Config',
22 ['program',
23 'hw_design',
24 'odm',
25 'hw_design_config',
26 'device_brand',
C Shapiro2f0bb5d2020-04-14 10:07:47 -050027 'device_signer_config',
David Burger7fd1dbe2020-03-26 09:26:55 -060028 'oem',
29 'sw_config',
30 'brand_config',
31 'build_target'])
32
33
34def ParseArgs(argv):
35 """Parse the available arguments.
36
37 Invalid arguments or -h cause this function to print a message and exit.
38
39 Args:
40 argv: List of string arguments (excluding program name / argv[0])
41
42 Returns:
43 argparse.Namespace object containing the attributes.
44 """
45 parser = argparse.ArgumentParser(
46 description='Converts source proto config into platform JSON config.')
47 parser.add_argument(
48 '-c',
49 '--project_configs',
50 nargs='+',
51 type=str,
52 help='Space delimited list of source protobinary project config files.')
53 parser.add_argument(
54 '-p',
55 '--program_config',
56 type=str,
57 help='Path to the source program-level protobinary file')
58 parser.add_argument(
59 '-o',
60 '--output',
61 type=str,
62 help='Output file that will be generated')
63 return parser.parse_args(argv)
64
65
66def _Set(field, target, target_name):
67 if field:
68 target[target_name] = field
69
70
71def _BuildArc(config):
72 if config.build_target.arc:
73 build_properties = {
74 'device': config.build_target.arc.device,
75 'first-api-level': config.build_target.arc.first_api_level,
76 'marketing-name': config.device_brand.brand_name,
77 'metrics-tag': config.hw_design.name.lower(),
Andrew Lambb47b7dc2020-04-07 10:20:32 -060078 'product': config.build_target.id.value,
David Burger7fd1dbe2020-03-26 09:26:55 -060079 }
80 if config.oem:
81 build_properties['oem'] = config.oem.name
82 return {
83 'build-properties': build_properties
84 }
85
C Shapiro90fda252020-04-17 14:34:57 -050086def _BuildBluetooth(config, bluetooth_files):
87 bt_flags = config.sw_config.bluetooth_config.flags
88 # Convert to native map (from proto wrapper)
89 bt_flags_map = dict(bt_flags)
90 result = {}
91 if bt_flags_map:
92 result['flags'] = bt_flags_map
93 bt_comp = config.hw_design_config.hardware_features.bluetooth.component
94 if bt_comp.vendor_id:
95 bt_id = _BluetoothId(config.hw_design.name.lower(), bt_comp)
96 if bt_id in bluetooth_files:
97 result['config'] = bluetooth_files[bt_id]
98 return result
99
David Burger7fd1dbe2020-03-26 09:26:55 -0600100
101def _BuildFingerprint(hw_topology):
Andrew Lambc2c55462020-04-06 08:43:34 -0600102 if hw_topology.HasField('fingerprint'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600103 fp = hw_topology.fingerprint.hardware_feature.fingerprint
104 location = fp.Location.DESCRIPTOR.values_by_number[fp.location].name
105 result = {
106 'sensor-location': location.lower().replace('_', '-'),
107 }
108 if fp.board:
109 result['board'] = fp.board
110 return result
111
112
113def _FwBcsPath(payload):
114 if payload and payload.firmware_image_name:
115 return 'bcs://%s.%d.%d.0.tbz2' % (
116 payload.firmware_image_name,
117 payload.version.major,
118 payload.version.minor)
119
120
121def _FwBuildTarget(payload):
122 if payload:
123 return payload.build_target_name
124
125
126def _BuildFirmware(config):
David Burger7fd1dbe2020-03-26 09:26:55 -0600127 fw = config.sw_config.firmware
128 main_ro = fw.main_ro_payload
129 main_rw = fw.main_rw_payload
130 ec_ro = fw.ec_ro_payload
131 pd_ro = fw.pd_ro_payload
132
133 build_targets = {}
134 _Set(_FwBuildTarget(main_ro), build_targets, 'depthcharge')
135 # Default to RO build target if no RW set
136 _Set(_FwBuildTarget(main_rw) or _FwBuildTarget(main_ro),
137 build_targets,
138 'coreboot')
139 _Set(_FwBuildTarget(ec_ro), build_targets, 'ec')
140 _Set(list(fw.ec_extras), build_targets, 'ec_extras')
141 # Default to EC build target if no PD set
142 _Set(_FwBuildTarget(pd_ro) or _FwBuildTarget(ec_ro),
143 build_targets,
144 'libpayload')
145
146 result = {
147 'bcs-overlay': config.build_target.overlay_name,
148 'build-targets': build_targets,
David Burger7fd1dbe2020-03-26 09:26:55 -0600149 }
Andrew Lamb883fa042020-04-06 11:37:22 -0600150
151 _Set(main_ro.firmware_image_name.lower(), result, 'image-name')
152
153 if not any((
154 main_ro.firmware_image_name,
155 main_rw.firmware_image_name,
156 ec_ro.firmware_image_name,
157 pd_ro.firmware_image_name,
158 )):
Andrew Lambb9e660f2020-04-06 11:37:22 -0600159 result['no-firmware'] = True
Andrew Lamb883fa042020-04-06 11:37:22 -0600160
161 _Set(_FwBcsPath(main_ro), result, 'main-ro-image')
162 _Set(_FwBcsPath(main_rw), result, 'main-rw-image')
163 _Set(_FwBcsPath(ec_ro), result, 'ec-ro-image')
164 _Set(_FwBcsPath(pd_ro), result, 'pd-ro-image')
David Burger7fd1dbe2020-03-26 09:26:55 -0600165
Andrew Lambf39fbe82020-04-13 16:14:33 -0600166 _Set(
167 config.hw_design_config.hardware_features.fw_config.value,
168 result,
169 'firmware-config',
170 )
171
David Burger7fd1dbe2020-03-26 09:26:55 -0600172 return result
173
174
175def _BuildFwSigning(config):
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500176 if config.sw_config.firmware and config.device_signer_config:
177 return {
178 'key-id': config.device_signer_config.key_id,
179 'signature-id': config.hw_design.name.lower(),
180 }
181 return {}
David Burger7fd1dbe2020-03-26 09:26:55 -0600182
183
184def _File(source, destination):
185 return {
186 'destination': destination,
187 'source': source
188 }
189
190
191def _BuildAudio(config):
192 alsa_path = '/usr/share/alsa/ucm'
193 cras_path = '/etc/cras'
194 project_name = config.hw_design.name.lower()
Andrew Lamb7d536782020-04-07 10:23:55 -0600195 if not config.sw_config.HasField('audio_config'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600196 return {}
197 audio = config.sw_config.audio_config
198 card = audio.card_name
David Burger599ff7b2020-04-06 16:29:31 -0600199 card_with_suffix = audio.card_name
200 if audio.ucm_suffix:
201 card_with_suffix += '.' + audio.ucm_suffix
David Burger7fd1dbe2020-03-26 09:26:55 -0600202 files = []
203 if audio.ucm_file:
David Burger599ff7b2020-04-06 16:29:31 -0600204 files.append(_File(
205 audio.ucm_file,
206 '%s/%s/HiFi.conf' % (alsa_path, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600207 if audio.ucm_master_file:
208 files.append(_File(
David Burger599ff7b2020-04-06 16:29:31 -0600209 audio.ucm_master_file,
210 '%s/%s/%s.conf' % (alsa_path, card_with_suffix, card_with_suffix)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600211 if audio.card_config_file:
212 files.append(_File(
213 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
214 if audio.dsp_file:
215 files.append(
David Burger2e254902020-04-02 16:56:01 -0600216 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burger599ff7b2020-04-06 16:29:31 -0600217
218 result = {
David Burger7fd1dbe2020-03-26 09:26:55 -0600219 'main': {
220 'cras-config-dir': project_name,
221 'files': files,
222 }
223 }
David Burger599ff7b2020-04-06 16:29:31 -0600224 if audio.ucm_suffix:
David Burger03cdcbd2020-04-13 13:54:48 -0600225 result['main']['ucm-suffix'] = audio.ucm_suffix
David Burger599ff7b2020-04-06 16:29:31 -0600226
227 return result
David Burger7fd1dbe2020-03-26 09:26:55 -0600228
229
David Burger8aa8fa32020-04-14 08:30:34 -0600230def _BuildCamera(hw_topology):
231 if hw_topology.HasField('camera'):
232 camera = hw_topology.camera.hardware_feature.camera
233 result = {}
234 if camera.count.value:
235 result['count'] = camera.count.value
236 return result
237
238
Andrew Lamb7806ce92020-04-07 10:22:17 -0600239def _BuildIdentity(hw_scan_config, program, brand_scan_config=None):
David Burger7fd1dbe2020-03-26 09:26:55 -0600240 identity = {}
241 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
242 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
Andrew Lamb7806ce92020-04-07 10:22:17 -0600243 # 'platform-name' is needed to support 'mosys platform name'. Clients should
244 # longer require platform name, but set it here for backwards compatibility.
245 _Set(program.name, identity, 'platform-name')
David Burger7fd1dbe2020-03-26 09:26:55 -0600246 # ARM architecture
247 _Set(hw_scan_config.device_tree_compatible_match, identity,
248 'device-tree-compatible-match')
249
250 if brand_scan_config:
251 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
252
253 return identity
254
255
256def _Lookup(id_value, id_map):
257 if id_value.value:
258 key = id_value.value
259 if key in id_map:
260 return id_map[id_value.value]
261 error = 'Failed to lookup %s with value: %s' % (
262 id_value.__class__.__name__.replace('Id', ''), key)
263 print(error)
264 print('Check the config contents provided:')
265 pp = pprint.PrettyPrinter(indent=4)
266 pp.pprint(id_map)
267 raise Exception(error)
268
269
C Shapiro90fda252020-04-17 14:34:57 -0500270def _TransformBuildConfigs(config, bluetooth_files={}):
David Burger7fd1dbe2020-03-26 09:26:55 -0600271 partners = dict([(x.id.value, x) for x in config.partners.value])
272 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600273 sw_configs = list(config.software_configs)
274 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
275
C Shapiroa0b766c2020-03-31 08:35:28 -0500276 if len(config.build_targets) != 1:
277 # Artifact of sharing the config_bundle for analysis and transforms.
278 # Integrated analysis of multiple programs/projects it the only time
279 # having multiple build targets would be valid.
280 raise Exception('Single build_target required for transform')
281
David Burger7fd1dbe2020-03-26 09:26:55 -0600282 results = {}
283 for hw_design in config.designs.value:
284 if config.device_brands.value:
285 device_brands = [x for x in config.device_brands.value
286 if x.design_id.value == hw_design.id.value]
287 else:
288 device_brands = [device_brand_pb2.DeviceBrand()]
289
290 for device_brand in device_brands:
291 # Brand config can be empty since platform JSON config allows it
292 brand_config = brand_config_pb2.BrandConfig()
293 if device_brand.id.value in brand_configs:
294 brand_config = brand_configs[device_brand.id.value]
295
296 for hw_design_config in hw_design.configs:
297 design_id = hw_design_config.id.value
298 sw_config_matches = [x for x in sw_configs
299 if x.design_config_id.value == design_id]
300 if len(sw_config_matches) == 1:
301 sw_config = sw_config_matches[0]
302 elif len(sw_config_matches) > 1:
303 raise Exception('Multiple software configs found for: %s' % design_id)
304 else:
305 raise Exception('Software config is required for: %s' % design_id)
306
C Shapiro2f0bb5d2020-04-14 10:07:47 -0500307 program = _Lookup(hw_design.program_id, programs)
308 signer_configs = dict(
309 [(x.brand_id.value, x) for x in program.device_signer_configs])
310 device_signer_config = None
311 if signer_configs:
312 device_signer_config = _Lookup(device_brand.id, signer_configs)
313
C Shapiro90fda252020-04-17 14:34:57 -0500314 transformed_config = _TransformBuildConfig(
315 Config(
316 program=program,
317 hw_design=hw_design,
318 odm=_Lookup(hw_design.odm_id, partners),
319 hw_design_config=hw_design_config,
320 device_brand=device_brand,
321 device_signer_config=device_signer_config,
322 oem=_Lookup(device_brand.oem_id, partners),
323 sw_config=sw_config,
324 brand_config=brand_config,
325 build_target=config.build_targets[0]),
326 bluetooth_files)
David Burger7fd1dbe2020-03-26 09:26:55 -0600327
328 config_json = json.dumps(transformed_config,
329 sort_keys=True,
330 indent=2,
331 separators=(',', ': '))
332
333 if config_json not in results:
334 results[config_json] = transformed_config
335
336 return list(results.values())
337
338
C Shapiro90fda252020-04-17 14:34:57 -0500339def _TransformBuildConfig(config, bluetooth_files):
David Burger7fd1dbe2020-03-26 09:26:55 -0600340 """Transforms Config instance into target platform JSON schema.
341
342 Args:
343 config: Config namedtuple
C Shapiro90fda252020-04-17 14:34:57 -0500344 bluetooth_files: Map to look up the generated bluetooth config files.
David Burger7fd1dbe2020-03-26 09:26:55 -0600345
346 Returns:
347 Unique config payload based on the platform JSON schema.
348 """
349 result = {
350 'identity': _BuildIdentity(
351 config.sw_config.id_scan_config,
Andrew Lamb7806ce92020-04-07 10:22:17 -0600352 config.program,
David Burger7fd1dbe2020-03-26 09:26:55 -0600353 config.brand_config.scan_config),
354 'name': config.hw_design.name.lower(),
355 }
356
357 _Set(_BuildArc(config), result, 'arc')
358 _Set(_BuildAudio(config), result, 'audio')
C Shapiro90fda252020-04-17 14:34:57 -0500359 _Set(_BuildBluetooth(config, bluetooth_files), result, 'bluetooth')
David Burger7fd1dbe2020-03-26 09:26:55 -0600360 _Set(config.device_brand.brand_code, result, 'brand-code')
David Burger8aa8fa32020-04-14 08:30:34 -0600361 _Set(_BuildCamera(
362 config.hw_design_config.hardware_topology), result, 'camera')
David Burger7fd1dbe2020-03-26 09:26:55 -0600363 _Set(_BuildFirmware(config), result, 'firmware')
364 _Set(_BuildFwSigning(config), result, 'firmware-signing')
365 _Set(_BuildFingerprint(
366 config.hw_design_config.hardware_topology), result, 'fingerprint')
367 power_prefs = config.sw_config.power_config.preferences
368 power_prefs_map = dict(
369 (x.replace('_', '-'),
370 power_prefs[x]) for x in power_prefs)
371 _Set(power_prefs_map, result, 'power')
372
373 return result
374
375
376def WriteOutput(configs, output=None):
377 """Writes a list of configs to platform JSON format.
378
379 Args:
380 configs: List of config dicts defined in cros_config_schema.yaml
381 output: Target file output (if None, prints to stdout)
382 """
383 json_output = json.dumps(
384 {'chromeos': {
385 'configs': configs,
386 }},
387 sort_keys=True,
388 indent=2,
389 separators=(',', ': '))
390 if output:
391 with open(output, 'w') as output_stream:
392 # Using print function adds proper trailing newline.
393 print(json_output, file=output_stream)
394 else:
395 print(json_output)
396
397
C Shapiro90fda252020-04-17 14:34:57 -0500398def _BluetoothId(project_name, bt_comp):
399 return '_'.join([project_name,
400 bt_comp.vendor_id,
401 bt_comp.product_id,
402 bt_comp.bcd_device])
403
404
405def WriteBluetoothConfigFiles(config, output_dir):
406 """Writes bluetooth conf files for every unique bluetooth chip.
407
408 Args:
409 config: Source ConfigBundle to process.
410 output_dir: Path to the generated output.
411 Returns:
412 dict that maps the bluetooth component id onto the file config.
413 """
414 project_gen_path = re.match(r'.*(generated.*)', output_dir).groups(1)[0]
415 result = {}
416 for hw_design in config.designs.value:
417 project_name = hw_design.name.lower()
418 for design_config in hw_design.configs:
419 bt_comp = design_config.hardware_features.bluetooth.component
420 if bt_comp.vendor_id:
421 bt_id = _BluetoothId(project_name, bt_comp)
422 result[bt_id] = {
423 'build-path': '%s/%s/bluetooth/%s.conf' % (
424 project_name, project_gen_path, bt_id),
425 'system-path': '/etc/bluetooth/%s/main.conf' % bt_id,
426 }
427 bt_content = '''[General]
428DeviceID = bluetooth:%s:%s:%s''' % (bt_comp.vendor_id,
429 bt_comp.product_id,
430 bt_comp.bcd_device)
431
432 output = '%s/bluetooth/%s.conf' % (output_dir, bt_id)
433 with open(output, 'w') as output_stream:
434 # Using print function adds proper trailing newline.
435 print(bt_content, file=output_stream)
436 return result
437
438
David Burger7fd1dbe2020-03-26 09:26:55 -0600439def _ReadConfig(path):
440 """Reads a binary proto from a file.
441
442 Args:
443 path: Path to the binary proto.
444 """
445 config = config_bundle_pb2.ConfigBundle()
446 with open(path, 'rb') as f:
447 config.ParseFromString(f.read())
448 return config
449
450
451def _MergeConfigs(configs):
452 result = config_bundle_pb2.ConfigBundle()
453 for config in configs:
454 result.MergeFrom(config)
455
456 return result
457
458
459def Main(project_configs,
460 program_config,
461 output):
462 """Transforms source proto config into platform JSON.
463
464 Args:
465 project_configs: List of source project configs to transform.
466 program_config: Program config for the given set of projects.
467 output: Output file that will be generated by the transform.
468 """
C Shapiro90fda252020-04-17 14:34:57 -0500469 configs =_MergeConfigs(
470 [_ReadConfig(program_config)] +
471 [_ReadConfig(config) for config in project_configs])
472 bt_files = {}
473 # Extracts output directory through regex versus separate args
474 if output and 'generated' in output:
475 bt_files = WriteBluetoothConfigFiles(configs, os.path.dirname(output))
476 WriteOutput(_TransformBuildConfigs(configs, bt_files), output)
David Burger7fd1dbe2020-03-26 09:26:55 -0600477
478
479def main(argv=None):
480 """Main program which parses args and runs
481
482 Args:
483 argv: List of command line arguments, if None uses sys.argv.
484 """
485 if argv is None:
486 argv = sys.argv[1:]
487 opts = ParseArgs(argv)
488 Main(opts.project_configs, opts.program_config, opts.output)
489
490
491if __name__ == '__main__':
492 sys.exit(main(sys.argv[1:]))