1#!/usr/bin/env python3
2
3# Copyright (c) 2019 - 2020 Nordic Semiconductor ASA
4# Copyright (c) 2019 Linaro Limited
5# Copyright (c) 2024 SILA Embedded Solutions GmbH
6# Copyright 2025 NXP
7# SPDX-License-Identifier: Apache-2.0
8
9# This script uses edtlib to generate a pickled edt from a devicetree
10# (.dts) file. Information from binding files in YAML format is used
11# as well.
12#
13# Bindings are files that describe devicetree nodes. Devicetree nodes are
14# usually mapped to bindings via their 'compatible = "..."' property.
15#
16# See Zephyr's Devicetree user guide for details.
17#
18# Note: Do not access private (_-prefixed) identifiers from edtlib here (and
19# also note that edtlib is not meant to expose the dtlib API directly).
20# Instead, think of what API you need, and add it as a public documented API in
21# edtlib. This will keep this script simple.
22
23import argparse
24import os
25import pickle
26import sys
27from typing import NoReturn
28
29sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'python-devicetree',
30                                'src'))
31
32import edtlib_logger
33from devicetree import edtlib
34
35
36def main():
37    args = parse_args()
38
39    edtlib_logger.setup_edtlib_logging()
40
41    vendor_prefixes = {}
42    for prefixes_file in args.vendor_prefixes:
43        vendor_prefixes.update(edtlib.load_vendor_prefixes_txt(prefixes_file))
44
45    try:
46        edt = edtlib.EDT(args.dts, args.bindings_dirs,
47                         workspace_dir=args.workspace_dir,
48                         # Suppress this warning if it's suppressed in dtc
49                         warn_reg_unit_address_mismatch=
50                             "-Wno-simple_bus_reg" not in args.dtc_flags,
51                         default_prop_types=True,
52                         infer_binding_for_paths=["/zephyr,user", "/cpus"],
53                         werror=args.edtlib_Werror,
54                         vendor_prefixes=vendor_prefixes,
55                         warn_bus_mismatch=args.warn_bus_mismatch)
56    except edtlib.EDTError as e:
57        sys.exit(f"devicetree error: {e}")
58
59    # Save merged DTS source, as a debugging aid
60    with open(args.dts_out, "w", encoding="utf-8") as f:
61        print(edt.dts_source, file=f)
62
63    write_pickled_edt(edt, args.edt_pickle_out)
64
65
66def parse_args() -> argparse.Namespace:
67    # Returns parsed command-line arguments
68
69    parser = argparse.ArgumentParser(allow_abbrev=False)
70    parser.add_argument("--dts", required=True, help="DTS file")
71    parser.add_argument("--dtc-flags",
72                        help="'dtc' devicetree compiler flags, some of which "
73                             "might be respected here")
74    parser.add_argument("--bindings-dirs", nargs='+', required=True,
75                        help="directory with bindings in YAML format, "
76                        "we allow multiple")
77    parser.add_argument("--workspace-dir", default=os.getcwd(),
78                        help="directory to be used as reference for generated "
79                        "relative paths (e.g. WEST_TOPDIR)")
80    parser.add_argument("--dts-out", required=True,
81                        help="path to write merged DTS source code to (e.g. "
82                             "as a debugging aid)")
83    parser.add_argument("--edt-pickle-out",
84                        help="path to write pickled edtlib.EDT object to", required=True)
85    parser.add_argument("--vendor-prefixes", action='append', default=[],
86                        help="vendor-prefixes.txt path; used for validation; "
87                             "may be given multiple times")
88    parser.add_argument("--edtlib-Werror", action="store_true",
89                        help="if set, edtlib-specific warnings become errors. "
90                             "(this does not apply to warnings shared "
91                             "with dtc.)")
92    parser.add_argument("--warn-bus-mismatch", action="store_true",
93                        help="warn when devicetree nodes are on buses that "
94                             "don't match available binding expectations")
95
96    return parser.parse_args()
97
98
99def write_pickled_edt(edt: edtlib.EDT, out_file: str) -> None:
100    # Writes the edt object in pickle format to out_file.
101
102    with open(out_file, 'wb') as f:
103        # Pickle protocol version 4 is the default as of Python 3.8
104        # and was introduced in 3.4, so it is both available and
105        # recommended on all versions of Python that Zephyr supports
106        # (at time of writing, Python 3.6 was Zephyr's minimum
107        # version, and 3.10 the most recent CPython release).
108        #
109        # Using a common protocol version here will hopefully avoid
110        # reproducibility issues in different Python installations.
111        pickle.dump(edt, f, protocol=4)
112
113
114def err(s: str) -> NoReturn:
115    raise Exception(s)
116
117
118if __name__ == "__main__":
119    main()
120