text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```yaml description: Property default value test compatible: "defaults" properties: int: type: int required: false default: 123 array: type: array required: false default: [1, 2, 3] uint8-array: type: uint8-array required: false default: [0x89, 0xAB, 0xCD] string: type: string required: false default: "hello" string-array: type: string-array required: false default: ["hello", "there"] default-not-used: type: int required: false default: 123 ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/defaults.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
157
```yaml description: Include ordering test compatible: "order-1" include: ["foo-required.yaml", "foo-optional.yaml"] ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/order-1.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```yaml description: GPIO destination for mapping test compatible: "gpio-dst" gpio-cells: - val ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/gpio-dst.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
25
```yaml description: Device on bar bus compatible: "on-bus" on-bus: "bar" ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/device-on-bar-bus.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
23
```yaml description: Interrupt controller with two cells compatible: "interrupt-two-cell" interrupt-cells: - one - two ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/interrupt-2-cell.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
29
```yaml description: Device on foo bus compatible: "on-bus" on-bus: "foo" ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/device-on-foo-bus.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
23
```yaml properties: foo: required: false type: int baz: required: true type: int ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/grandchild-1.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
30
```yaml include: [grandchild-1.yaml, grandchild-2.yaml, grandchild-3.yaml] properties: bar: required: true type: int ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/child.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
38
```yaml properties: foo: type: int required: false ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/foo-optional.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
16
```yaml description: Include ordering test compatible: "order-2" include: ["foo-optional.yaml", "foo-required.yaml"] ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/order-2.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```yaml properties: baz: required: true type: int ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/grandchild-2.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
17
```yaml properties: foo: type: int required: true ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/foo-required.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
16
```yaml # A file that mentions a 'compatible' string without actually implementing it. # Used to check for issues with how we optimize binding loading. # props ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/false-positive.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
32
```yaml description: Device.props test compatible: "props" properties: nonexistent-boolean: type: boolean existent-boolean: type: boolean int: type: int const: 1 array: type: array uint8-array: type: uint8-array string: type: string const: "foo" string-array: type: string-array const: ['foo', 'bar', 'baz'] phandle-ref: type: phandle phandle-refs: type: phandles phandle-array-foos: type: phandle-array phandle-array-foo-names: type: string-array # There's some slight special-casing for GPIOs in that 'foo-gpios = ...' # gets resolved to #gpio-cells rather than #foo-gpio-cells, so test that # too foo-gpios: type: phandle-array path: type: path ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/props.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
225
```yaml description: Controller with two data values compatible: "phandle-array-controller-2" phandle-array-foo-cells: - one - two ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/phandle-array-controller-2.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
36
```yaml description: Interrupt controller with one cell compatible: "interrupt-one-cell" interrupt-cells: - one ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/interrupt-1-cell.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
25
```yaml description: Binding in test-bindings-2/ compatible: "in-dir-2" ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings-2/multidir.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
20
```python __all__ = ['edtlib', 'dtlib'] ```
/content/code_sandbox/scripts/dts/python-devicetree/src/devicetree/__init__.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
15
```yaml description: Property enum test compatible: "enums" properties: int-enum: type: int enum: - 1 - 2 - 3 string-enum: # not tokenizable type: string enum: - foo bar - foo_bar tokenizable-lower-enum: # tokenizable in lowercase only type: string enum: - bar - BAR tokenizable-enum: # tokenizable in lower and uppercase type: string enum: - bar - whitespace is ok - 123 is ok no-enum: type: string ```
/content/code_sandbox/scripts/dts/python-devicetree/tests/test-bindings/enums.yaml
yaml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
154
```python # Tip: You can view just the documentation with 'pydoc3 devicetree.dtlib' """ A library for extracting information from .dts (devicetree) files. See the documentation for the DT and Node classes for more information. The top-level entry point of the library is the DT class. DT.__init__() takes a .dts file to parse and a list of directories to search for any /include/d files. """ import collections import enum import errno import os import re import string import sys import textwrap from typing import Any, Dict, Iterable, List, \ NamedTuple, NoReturn, Optional, Set, Tuple, TYPE_CHECKING, Union # NOTE: tests/test_dtlib.py is the test suite for this library. class DTError(Exception): "Exception raised for devicetree-related errors" class Node: r""" Represents a node in the devicetree ('node-name { ... };'). These attributes are available on Node instances: name: The name of the node (a string). unit_addr: The portion after the '@' in the node's name, or the empty string if the name has no '@' in it. Note that this is a string. Run int(node.unit_addr, 16) to get an integer. props: A dict that maps the properties defined on the node to their values. 'props' is indexed by property name (a string), and values are Property objects. To convert property values to Python numbers or strings, use dtlib.to_num(), dtlib.to_nums(), or dtlib.to_string(). Property values are represented as 'bytes' arrays to support the full generality of DTS, which allows assignments like x = "foo", < 0x12345678 >, [ 9A ]; This gives x the value b"foo\0\x12\x34\x56\x78\x9A". Numbers in DTS are stored in big-endian format. nodes: A dict containing the subnodes of the node, indexed by name. labels: A list with all labels pointing to the node, in the same order as the labels appear, but with duplicates removed. 'label_1: label_2: node { ... };' gives 'labels' the value ["label_1", "label_2"]. parent: The parent Node of the node. 'None' for the root node. path: The path to the node as a string, e.g. "/foo/bar". dt: The DT instance this node belongs to. """ # # Public interface # def __init__(self, name: str, parent: Optional['Node'], dt: 'DT'): """ Node constructor. Not meant to be called directly by clients. """ # Remember to update DT.__deepcopy__() if you change this. self._name = name self.props: Dict[str, 'Property'] = {} self.nodes: Dict[str, 'Node'] = {} self.labels: List[str] = [] self.parent = parent self.dt = dt self._omit_if_no_ref = False self._is_referenced = False if name.count("@") > 1: dt._parse_error("multiple '@' in node name") if not name == "/": for char in name: if char not in _nodename_chars: dt._parse_error(f"{self.path}: bad character '{char}' " "in node name") @property def name(self) -> str: """ See the class documentation. """ # Converted to a property to discourage renaming -- that has to be done # via DT.move_node. return self._name @property def unit_addr(self) -> str: """ See the class documentation. """ return self.name.partition("@")[2] @property def path(self) -> str: """ See the class documentation. """ node_names = [] # This dynamic computation is required to be able to move # nodes in the DT class. cur = self while cur.parent: node_names.append(cur.name) cur = cur.parent return "/" + "/".join(reversed(node_names)) def node_iter(self) -> Iterable['Node']: """ Returns a generator for iterating over the node and its children, recursively. For example, this will iterate over all nodes in the tree (like dt.node_iter()). for node in dt.root.node_iter(): ... """ yield self for node in self.nodes.values(): yield from node.node_iter() def _get_prop(self, name: str) -> 'Property': # Returns the property named 'name' on the node, creating it if it # doesn't already exist prop = self.props.get(name) if not prop: prop = Property(self, name) self.props[name] = prop return prop def _del(self) -> None: # Removes the node from the tree. When called on the root node, # this method will leave it empty but still part of the tree. if self.parent is None: self.nodes.clear() self.props.clear() return self.parent.nodes.pop(self.name) # type: ignore def __str__(self): """ Returns a DTS representation of the node. Called automatically if the node is print()ed. """ s = "".join(label + ": " for label in self.labels) s += f"{self.name} {{\n" for prop in self.props.values(): s += "\t" + str(prop) + "\n" for child in self.nodes.values(): s += textwrap.indent(child.__str__(), "\t") + "\n" s += "};" return s def __repr__(self): """ Returns some information about the Node instance. Called automatically if the Node instance is evaluated. """ return f"<Node {self.path} in '{self.dt.filename}'>" # See Property.type class Type(enum.IntEnum): EMPTY = 0 BYTES = 1 NUM = 2 NUMS = 3 STRING = 4 STRINGS = 5 PATH = 6 PHANDLE = 7 PHANDLES = 8 PHANDLES_AND_NUMS = 9 COMPOUND = 10 class _MarkerType(enum.IntEnum): # Types of markers in property values # References PATH = 0 # &foo PHANDLE = 1 # <&foo> LABEL = 2 # foo: <1 2 3> # Start of data blocks of specific type UINT8 = 3 # [00 01 02] (and also used for /incbin/) UINT16 = 4 # /bits/ 16 <1 2 3> UINT32 = 5 # <1 2 3> UINT64 = 6 # /bits/ 64 <1 2 3> STRING = 7 # "foo" class Property: """ Represents a property ('x = ...'). These attributes are available on Property instances: name: The name of the property (a string). value: The value of the property, as a 'bytes' string. Numbers are stored in big-endian format, and strings are null-terminated. Putting multiple comma-separated values in an assignment (e.g., 'x = < 1 >, "foo"') will concatenate the values. See the to_*() methods for converting the value to other types. type: The type of the property, inferred from the syntax used in the assignment. This is one of the following constants (with example assignments): Assignment | Property.type ----------------------------+------------------------ foo; | dtlib.Type.EMPTY foo = []; | dtlib.Type.BYTES foo = [01 02]; | dtlib.Type.BYTES foo = /bits/ 8 <1>; | dtlib.Type.BYTES foo = <1>; | dtlib.Type.NUM foo = <>; | dtlib.Type.NUMS foo = <1 2 3>; | dtlib.Type.NUMS foo = <1 2>, <3>; | dtlib.Type.NUMS foo = "foo"; | dtlib.Type.STRING foo = "foo", "bar"; | dtlib.Type.STRINGS foo = <&l>; | dtlib.Type.PHANDLE foo = <&l1 &l2 &l3>; | dtlib.Type.PHANDLES foo = <&l1 &l2>, <&l3>; | dtlib.Type.PHANDLES foo = <&l1 1 2 &l2 3 4>; | dtlib.Type.PHANDLES_AND_NUMS foo = <&l1 1 2>, <&l2 3 4>; | dtlib.Type.PHANDLES_AND_NUMS foo = &l; | dtlib.Type.PATH *Anything else* | dtlib.Type.COMPOUND *Anything else* includes properties mixing phandle (<&label>) and node path (&label) references with other data. Data labels in the property value do not influence the type. labels: A list with all labels pointing to the property, in the same order as the labels appear, but with duplicates removed. 'label_1: label2: x = ...' gives 'labels' the value ["label_1", "label_2"]. offset_labels: A dictionary that maps any labels within the property's value to their offset, in bytes. For example, 'x = < 0 label_1: 1 label_2: >' gives 'offset_labels' the value {"label_1": 4, "label_2": 8}. Iteration order will match the order of the labels on Python versions that preserve dict insertion order. node: The Node the property is on. """ # # Public interface # def __init__(self, node: Node, name: str): # Remember to update DT.__deepcopy__() if you change this. if "@" in name: node.dt._parse_error("'@' is only allowed in node names") self.name = name self.value = b"" self.labels: List[str] = [] # We have to wait to set this until later, when we've got # the entire tree. self.offset_labels: Dict[str, int] = {} self.node: Node = node self._label_offset_lst: List[Tuple[str, int]] = [] # A list of [offset, label, type] lists (sorted by offset), # giving the locations of references within the value. 'type' # is either _MarkerType.PATH, for a node path reference, # _MarkerType.PHANDLE, for a phandle reference, or # _MarkerType.LABEL, for a label on/within data. Node paths # and phandles need to be patched in after parsing. self._markers: List[List] = [] @property def type(self) -> Type: """ See the class documentation. """ # Data labels (e.g. 'foo = label: <3>') are irrelevant, so filter them # out types = [marker[1] for marker in self._markers if marker[1] != _MarkerType.LABEL] if not types: return Type.EMPTY if types == [_MarkerType.UINT8]: return Type.BYTES if types == [_MarkerType.UINT32]: return Type.NUM if len(self.value) == 4 else Type.NUMS # Treat 'foo = <1 2 3>, <4 5>, ...' as Type.NUMS too if set(types) == {_MarkerType.UINT32}: return Type.NUMS if set(types) == {_MarkerType.STRING}: return Type.STRING if len(types) == 1 else Type.STRINGS if types == [_MarkerType.PATH]: return Type.PATH if types == [_MarkerType.UINT32, _MarkerType.PHANDLE] and \ len(self.value) == 4: return Type.PHANDLE if set(types) == {_MarkerType.UINT32, _MarkerType.PHANDLE}: if len(self.value) == 4*types.count(_MarkerType.PHANDLE): # Array with just phandles in it return Type.PHANDLES # Array with both phandles and numbers return Type.PHANDLES_AND_NUMS return Type.COMPOUND def to_num(self, signed=False) -> int: """ Returns the value of the property as a number. Raises DTError if the property was not assigned with this syntax (has Property.type Type.NUM): foo = < 1 >; signed (default: False): If True, the value will be interpreted as signed rather than unsigned. """ if self.type is not Type.NUM: _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = < (number) >;', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) return int.from_bytes(self.value, "big", signed=signed) def to_nums(self, signed=False) -> List[int]: """ Returns the value of the property as a list of numbers. Raises DTError if the property was not assigned with this syntax (has Property.type Type.NUM or Type.NUMS): foo = < 1 2 ... >; signed (default: False): If True, the values will be interpreted as signed rather than unsigned. """ if self.type not in (Type.NUM, Type.NUMS): _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = < (number) (number) ... >;', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) return [int.from_bytes(self.value[i:i + 4], "big", signed=signed) for i in range(0, len(self.value), 4)] def to_bytes(self) -> bytes: """ Returns the value of the property as a raw 'bytes', like Property.value, except with added type checking. Raises DTError if the property was not assigned with this syntax (has Property.type Type.BYTES): foo = [ 01 ... ]; """ if self.type is not Type.BYTES: _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = [ (byte) (byte) ... ];', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) return self.value def to_string(self) -> str: """ Returns the value of the property as a string. Raises DTError if the property was not assigned with this syntax (has Property.type Type.STRING): foo = "string"; This function might also raise UnicodeDecodeError if the string is not valid UTF-8. """ if self.type is not Type.STRING: _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = \"string\";', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) try: ret = self.value.decode("utf-8")[:-1] # Strip null except UnicodeDecodeError: _err(f"value of property '{self.name}' ({self.value!r}) " f"on {self.node.path} in {self.node.dt.filename} " "is not valid UTF-8") return ret # The separate 'return' appeases the type checker. def to_strings(self) -> List[str]: """ Returns the value of the property as a list of strings. Raises DTError if the property was not assigned with this syntax (has Property.type Type.STRING or Type.STRINGS): foo = "string", "string", ... ; Also raises DTError if any of the strings are not valid UTF-8. """ if self.type not in (Type.STRING, Type.STRINGS): _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = \"string\", \"string\", ... ;', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) try: ret = self.value.decode("utf-8").split("\0")[:-1] except UnicodeDecodeError: _err(f"value of property '{self.name}' ({self.value!r}) " f"on {self.node.path} in {self.node.dt.filename} " "is not valid UTF-8") return ret # The separate 'return' appeases the type checker. def to_node(self) -> Node: """ Returns the Node the phandle in the property points to. Raises DTError if the property was not assigned with this syntax (has Property.type Type.PHANDLE). foo = < &bar >; """ if self.type is not Type.PHANDLE: _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = < &foo >;', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) return self.node.dt.phandle2node[int.from_bytes(self.value, "big")] def to_nodes(self) -> List[Node]: """ Returns a list with the Nodes the phandles in the property point to. Raises DTError if the property value contains anything other than phandles. All of the following are accepted: foo = < > foo = < &bar >; foo = < &bar &baz ... >; foo = < &bar ... >, < &baz ... >; """ def type_ok(): if self.type in (Type.PHANDLE, Type.PHANDLES): return True # Also accept 'foo = < >;' return self.type is Type.NUMS and not self.value if not type_ok(): _err("expected property '{0}' on {1} in {2} to be assigned with " "'{0} = < &foo &bar ... >;', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) return [self.node.dt.phandle2node[int.from_bytes(self.value[i:i + 4], "big")] for i in range(0, len(self.value), 4)] def to_path(self) -> Node: """ Returns the Node referenced by the path stored in the property. Raises DTError if the property was not assigned with either of these syntaxes (has Property.type Type.PATH or Type.STRING): foo = &bar; foo = "/bar"; For the second case, DTError is raised if the path does not exist. """ if self.type not in (Type.PATH, Type.STRING): _err("expected property '{0}' on {1} in {2} to be assigned with " "either '{0} = &foo' or '{0} = \"/path/to/node\"', not '{3}'" .format(self.name, self.node.path, self.node.dt.filename, self)) try: path = self.value.decode("utf-8")[:-1] except UnicodeDecodeError: _err(f"value of property '{self.name}' ({self.value!r}) " f"on {self.node.path} in {self.node.dt.filename} " "is not valid UTF-8") try: ret = self.node.dt.get_node(path) except DTError: _err(f"property '{self.name}' on {self.node.path} in " f"{self.node.dt.filename} points to the non-existent node " f'"{path}"') return ret # The separate 'return' appeases the type checker. def __str__(self): s = "".join(label + ": " for label in self.labels) + self.name if not self.value: return s + ";" s += " =" for i, (pos, marker_type, ref) in enumerate(self._markers): if i < len(self._markers) - 1: next_marker = self._markers[i + 1] else: next_marker = None # End of current marker end = next_marker[0] if next_marker else len(self.value) if marker_type is _MarkerType.STRING: # end - 1 to strip off the null terminator s += f' "{_decode_and_escape(self.value[pos:end - 1])}"' if end != len(self.value): s += "," elif marker_type is _MarkerType.PATH: s += " &" + ref if end != len(self.value): s += "," else: # <> or [] if marker_type is _MarkerType.LABEL: s += f" {ref}:" elif marker_type is _MarkerType.PHANDLE: s += " &" + ref pos += 4 # Subtle: There might be more data between the phandle and # the next marker, so we can't 'continue' here else: # marker_type is _MarkerType.UINT* elm_size = _TYPE_TO_N_BYTES[marker_type] s += _N_BYTES_TO_START_STR[elm_size] while pos != end: num = int.from_bytes(self.value[pos:pos + elm_size], "big") if elm_size == 1: s += f" {num:02X}" else: s += f" {hex(num)}" pos += elm_size if pos != 0 and \ (not next_marker or next_marker[1] not in (_MarkerType.PHANDLE, _MarkerType.LABEL)): s += _N_BYTES_TO_END_STR[elm_size] if pos != len(self.value): s += "," return s + ";" def __repr__(self): return f"<Property '{self.name}' at '{self.node.path}' in " \ f"'{self.node.dt.filename}'>" # # Internal functions # def _add_marker(self, marker_type: _MarkerType, data: Any = None): # Helper for registering markers in the value that are processed after # parsing. See _fixup_props(). 'marker_type' identifies the type of # marker, and 'data' has any optional data associated with the marker. # len(self.value) gives the current offset. This function is called # while the value is built. We use a list instead of a tuple to be able # to fix up offsets later (they might increase if the value includes # path references, e.g. 'foo = &bar, <3>;', which are expanded later). self._markers.append([len(self.value), marker_type, data]) # For phandle references, add a dummy value with the same length as a # phandle. This is handy for the length check in _register_phandles(). if marker_type is _MarkerType.PHANDLE: self.value += b"\0\0\0\0" class _T(enum.IntEnum): # Token IDs used by the DT lexer. # These values must be contiguous and start from 1. INCLUDE = 1 LINE = 2 STRING = 3 DTS_V1 = 4 PLUGIN = 5 MEMRESERVE = 6 BITS = 7 DEL_PROP = 8 DEL_NODE = 9 OMIT_IF_NO_REF = 10 LABEL = 11 CHAR_LITERAL = 12 REF = 13 INCBIN = 14 SKIP = 15 EOF = 16 # These values must be larger than the above contiguous range. NUM = 17 PROPNODENAME = 18 MISC = 19 BYTE = 20 BAD = 21 class _FileStackElt(NamedTuple): # Used for maintaining the /include/ stack. filename: str lineno: int contents: str pos: int _TokVal = Union[int, str] class _Token(NamedTuple): id: int val: _TokVal def __repr__(self): id_repr = _T(self.id).name return f'Token(id=_T.{id_repr}, val={repr(self.val)})' class DT: """ Represents a devicetree parsed from a .dts file (or from many files, if the .dts file /include/s other files). Creating many instances of this class is fine. The library has no global state. These attributes are available on DT instances: root: A Node instance representing the root (/) node. alias2node: A dictionary that maps maps alias strings (from /aliases) to Node instances label2node: A dictionary that maps each node label (a string) to the Node instance for the node. label2prop: A dictionary that maps each property label (a string) to a Property instance. label2prop_offset: A dictionary that maps each label (a string) within a property value (e.g., 'x = label_1: < 1 label2: 2 >;') to a (prop, offset) tuple, where 'prop' is a Property instance and 'offset' the byte offset (0 for label_1 and 4 for label_2 in the example). phandle2node: A dictionary that maps each phandle (a number) to a Node instance. memreserves: A list of (labels, address, length) tuples for the /memreserve/s in the .dts file, in the same order as they appear in the file. 'labels' is a possibly empty set with all labels preceding the memreserve (e.g., 'label1: label2: /memreserve/ ...'). 'address' and 'length' are numbers. filename: The filename passed to the DT constructor. """ # # Public interface # def __init__(self, filename: Optional[str], include_path: Iterable[str] = (), force: bool = False): """ Parses a DTS file to create a DT instance. Raises OSError if 'filename' can't be opened, and DTError for any parse errors. filename: Path to the .dts file to parse. (If None, an empty devicetree is created; this is unlikely to be what you want.) include_path: An iterable (e.g. list or tuple) containing paths to search for /include/d and /incbin/'d files. By default, files are only looked up relative to the .dts file that contains the /include/ or /incbin/. force: Try not to raise DTError even if the input tree has errors. For experimental use; results not guaranteed. """ # Remember to update __deepcopy__() if you change this. self._root: Optional[Node] = None self.alias2node: Dict[str, Node] = {} self.label2node: Dict[str, Node] = {} self.label2prop: Dict[str, Property] = {} self.label2prop_offset: Dict[str, Tuple[Property, int]] = {} self.phandle2node: Dict[int, Node] = {} self.memreserves: List[Tuple[Set[str], int, int]] = [] self.filename = filename self._force = force if filename is not None: self._parse_file(filename, include_path) else: self._include_path: List[str] = [] @property def root(self) -> Node: """ See the class documentation. """ # This is necessary because mypy can't tell that we never # treat self._root as a non-None value until it's initialized # properly in _parse_dt(). return self._root # type: ignore def get_node(self, path: str) -> Node: """ Returns the Node instance for the node with path or alias 'path' (a string). Raises DTError if the path or alias doesn't exist. For example, both dt.get_node("/foo/bar") and dt.get_node("bar-alias") will return the 'bar' node below: /dts-v1/; / { foo { bar_label: bar { baz { }; }; }; aliases { bar-alias = &bar-label; }; }; Fetching subnodes via aliases is supported: dt.get_node("bar-alias/baz") returns the 'baz' node. """ if path.startswith("/"): return _root_and_path_to_node(self.root, path, path) # Path does not start with '/'. First component must be an alias. alias, _, rest = path.partition("/") if alias not in self.alias2node: _err(f"no alias '{alias}' found -- did you forget the leading " "'/' in the node path?") return _root_and_path_to_node(self.alias2node[alias], rest, path) def has_node(self, path: str) -> bool: """ Returns True if the path or alias 'path' exists. See DT.get_node(). """ try: self.get_node(path) return True except DTError: return False def move_node(self, node: Node, new_path: str): """ Move a node 'node' to a new path 'new_path'. The entire subtree rooted at 'node' is moved along with it. You cannot move the root node or provide a 'new_path' value where a node already exists. This method raises an exception in both cases. As a restriction on the current implementation, the parent node of the new path must exist. """ if node is self.root: _err("the root node can't be moved") if self.has_node(new_path): _err(f"can't move '{node.path}' to '{new_path}': " 'destination node exists') if not new_path.startswith('/'): _err(f"path '{new_path}' doesn't start with '/'") for component in new_path.split('/'): for char in component: if char not in _nodename_chars: _err(f"new path '{new_path}': bad character '{char}'") old_name = node.name old_path = node.path new_parent_path, _, new_name = new_path.rpartition('/') if new_parent_path == '': # '/foo'.rpartition('/') is ('', '/', 'foo'). new_parent_path = '/' if not self.has_node(new_parent_path): _err(f"can't move '{old_path}' to '{new_path}': " f"parent node '{new_parent_path}' doesn't exist") new_parent = self.get_node(new_parent_path) if TYPE_CHECKING: assert new_parent is not None assert node.parent is not None del node.parent.nodes[old_name] node._name = new_name node.parent = new_parent new_parent.nodes[new_name] = node def node_iter(self) -> Iterable[Node]: """ Returns a generator for iterating over all nodes in the devicetree. For example, this will print the name of each node that has a property called 'foo': for node in dt.node_iter(): if "foo" in node.props: print(node.name) """ yield from self.root.node_iter() def __str__(self): """ Returns a DTS representation of the devicetree. Called automatically if the DT instance is print()ed. """ s = "/dts-v1/;\n\n" if self.memreserves: for labels, address, offset in self.memreserves: # List the labels in a consistent order to help with testing for label in labels: s += f"{label}: " s += f"/memreserve/ {address:#018x} {offset:#018x};\n" s += "\n" return s + str(self.root) def __repr__(self): """ Returns some information about the DT instance. Called automatically if the DT instance is evaluated. """ if self.filename: return f"DT(filename='{self.filename}', " \ f"include_path={self._include_path})" return super().__repr__() def __deepcopy__(self, memo): """ Implements support for the standard library copy.deepcopy() function on DT instances. """ # We need a new DT, obviously. Make a new, empty one. ret = DT(None, (), self._force) # Now allocate new Node objects for every node in self, to use # in the new DT. Set their parents to None for now and leave # them without any properties. We will recursively initialize # copies of parents before copies of children next. path2node_copy = { node.path: Node(node.name, None, ret) for node in self.node_iter() } # Point each copy of a node to the copy of its parent and set up # copies of each property. # # Share data when possible. For example, Property.value has # type 'bytes', which is immutable. We therefore don't need a # copy and can just point to the original data. for node in self.node_iter(): node_copy = path2node_copy[node.path] parent = node.parent if parent is not None: node_copy.parent = path2node_copy[parent.path] prop_name2prop_copy = { prop.name: Property(node_copy, prop.name) for prop in node.props.values() } for prop_name, prop_copy in prop_name2prop_copy.items(): prop = node.props[prop_name] prop_copy.value = prop.value prop_copy.labels = prop.labels[:] prop_copy.offset_labels = prop.offset_labels.copy() prop_copy._label_offset_lst = prop._label_offset_lst[:] prop_copy._markers = [marker[:] for marker in prop._markers] node_copy.props = prop_name2prop_copy node_copy.nodes = { child_name: path2node_copy[child_node.path] for child_name, child_node in node.nodes.items() } node_copy.labels = node.labels[:] node_copy._omit_if_no_ref = node._omit_if_no_ref node_copy._is_referenced = node._is_referenced # The copied nodes and properties are initialized, so # we can finish initializing the copied DT object now. ret._root = path2node_copy['/'] def copy_node_lookup_table(attr_name): original = getattr(self, attr_name) copy = { key: path2node_copy[original[key].path] for key in original } setattr(ret, attr_name, copy) copy_node_lookup_table('alias2node') copy_node_lookup_table('label2node') copy_node_lookup_table('phandle2node') ret_label2prop = {} for label, prop in self.label2prop.items(): node_copy = path2node_copy[prop.node.path] prop_copy = node_copy.props[prop.name] ret_label2prop[label] = prop_copy ret.label2prop = ret_label2prop ret_label2prop_offset = {} for label, prop_offset in self.label2prop_offset.items(): prop, offset = prop_offset node_copy = path2node_copy[prop.node.path] prop_copy = node_copy.props[prop.name] ret_label2prop_offset[label] = (prop_copy, offset) ret.label2prop_offset = ret_label2prop_offset ret.memreserves = [ (set(memreserve[0]), memreserve[1], memreserve[2]) for memreserve in self.memreserves ] ret.filename = self.filename return ret # # Parsing # def _parse_file(self, filename: str, include_path: Iterable[str]): self._include_path = list(include_path) with open(filename, encoding="utf-8") as f: self._file_contents = f.read() self._tok_i = self._tok_end_i = 0 self._filestack: List[_FileStackElt] = [] self._lexer_state: int = _DEFAULT self._saved_token: Optional[_Token] = None self._lineno: int = 1 self._parse_header() self._parse_memreserves() self._parse_dt() self._register_phandles() self._fixup_props() self._register_aliases() self._remove_unreferenced() self._register_labels() def _parse_header(self): # Parses /dts-v1/ (expected) and /plugin/ (unsupported) at the start of # files. There may be multiple /dts-v1/ at the start of a file. has_dts_v1 = False while self._peek_token().id == _T.DTS_V1: has_dts_v1 = True self._next_token() self._expect_token(";") # /plugin/ always comes after /dts-v1/ if self._peek_token().id == _T.PLUGIN: self._parse_error("/plugin/ is not supported") if not has_dts_v1: self._parse_error("expected '/dts-v1/;' at start of file") def _parse_memreserves(self): # Parses /memreserve/, which appears after /dts-v1/ while True: # Labels before /memreserve/ labels = [] while self._peek_token().id == _T.LABEL: _append_no_dup(labels, self._next_token().val) if self._peek_token().id == _T.MEMRESERVE: self._next_token() self.memreserves.append( (labels, self._eval_prim(), self._eval_prim())) self._expect_token(";") elif labels: self._parse_error("expected /memreserve/ after labels at " "beginning of file") else: return def _parse_dt(self): # Top-level parsing loop while True: tok = self._next_token() if tok.val == "/": # '/ { ... };', the root node if not self._root: self._root = Node(name="/", parent=None, dt=self) self._parse_node(self.root) elif tok.id in (_T.LABEL, _T.REF): # '&foo { ... };' or 'label: &foo { ... };'. The C tools only # support a single label here too. if tok.id == _T.LABEL: label = tok.val tok = self._next_token() if tok.id != _T.REF: self._parse_error("expected label reference (&foo)") else: label = None try: node = self._ref2node(tok.val) except DTError as e: self._parse_error(e) self._parse_node(node) if label: _append_no_dup(node.labels, label) elif tok.id == _T.DEL_NODE: self._next_ref2node()._del() self._expect_token(";") elif tok.id == _T.OMIT_IF_NO_REF: self._next_ref2node()._omit_if_no_ref = True self._expect_token(";") elif tok.id == _T.EOF: if not self._root: self._parse_error("no root node defined") return else: self._parse_error("expected '/' or label reference (&foo)") def _parse_node(self, node): # Parses the '{ ... };' part of 'node-name { ... };'. # We need to track which child nodes were defined in this set # of curly braces in order to reject duplicate node names. current_child_names = set() self._expect_token("{") while True: labels, omit_if_no_ref = self._parse_propnode_labels() tok = self._next_token() if tok.id == _T.PROPNODENAME: if self._peek_token().val == "{": # '<tok> { ...', expect node # Fetch the existing node if it already exists. This # happens when overriding nodes. child = node.nodes.get(tok.val) if child: if child.name in current_child_names: self._parse_error(f'{child.path}: duplicate node name') else: child = Node(name=tok.val, parent=node, dt=self) current_child_names.add(tok.val) for label in labels: _append_no_dup(child.labels, label) if omit_if_no_ref: child._omit_if_no_ref = True node.nodes[child.name] = child self._parse_node(child) else: # Not '<tok> { ...', expect property assignment if omit_if_no_ref: self._parse_error( "/omit-if-no-ref/ can only be used on nodes") prop = node._get_prop(tok.val) if self._check_token("="): self._parse_assignment(prop) elif not self._check_token(";"): # ';' is for an empty property, like 'foo;' self._parse_error("expected '{', '=', or ';'") for label in labels: _append_no_dup(prop.labels, label) elif tok.id == _T.DEL_NODE: tok2 = self._next_token() if tok2.id != _T.PROPNODENAME: self._parse_error("expected node name") if tok2.val in node.nodes: node.nodes[tok2.val]._del() self._expect_token(";") elif tok.id == _T.DEL_PROP: tok2 = self._next_token() if tok2.id != _T.PROPNODENAME: self._parse_error("expected property name") node.props.pop(tok2.val, None) self._expect_token(";") elif tok.val == "}": self._expect_token(";") return else: self._parse_error("expected node name, property name, or '}'") def _parse_propnode_labels(self): # _parse_node() helpers for parsing labels and /omit-if-no-ref/s before # nodes and properties. Returns a (<label list>, <omit-if-no-ref bool>) # tuple. labels = [] omit_if_no_ref = False while True: tok = self._peek_token() if tok.id == _T.LABEL: _append_no_dup(labels, tok.val) elif tok.id == _T.OMIT_IF_NO_REF: omit_if_no_ref = True elif (labels or omit_if_no_ref) and tok.id != _T.PROPNODENAME: # Got something like 'foo: bar: }' self._parse_error("expected node or property name") else: return labels, omit_if_no_ref self._next_token() def _parse_assignment(self, prop): # Parses the right-hand side of property assignment # # prop: # 'Property' instance being assigned # Remove any old value, path/phandle references, and in-value labels, # in case the property value is being overridden prop.value = b"" prop._markers = [] while True: # Parse labels before the value (e.g., '..., label: < 0 >') self._parse_value_labels(prop) tok = self._next_token() if tok.val == "<": self._parse_cells(prop, 4) elif tok.id == _T.BITS: n_bits = self._expect_num() if n_bits not in {8, 16, 32, 64}: self._parse_error("expected 8, 16, 32, or 64") self._expect_token("<") self._parse_cells(prop, n_bits//8) elif tok.val == "[": self._parse_bytes(prop) elif tok.id == _T.STRING: prop._add_marker(_MarkerType.STRING) prop.value += self._unescape(tok.val.encode("utf-8")) + b"\0" elif tok.id == _T.REF: prop._add_marker(_MarkerType.PATH, tok.val) elif tok.id == _T.INCBIN: self._parse_incbin(prop) else: self._parse_error("malformed value") # Parse labels after the value (e.g., '< 0 > label:, ...') self._parse_value_labels(prop) tok = self._next_token() if tok.val == ";": return if tok.val == ",": continue self._parse_error("expected ';' or ','") def _parse_cells(self, prop, n_bytes): # Parses '<...>' prop._add_marker(_N_BYTES_TO_TYPE[n_bytes]) while True: tok = self._peek_token() if tok.id == _T.REF: self._next_token() if n_bytes != 4: self._parse_error("phandle references are only allowed in " "arrays with 32-bit elements") prop._add_marker(_MarkerType.PHANDLE, tok.val) elif tok.id == _T.LABEL: prop._add_marker(_MarkerType.LABEL, tok.val) self._next_token() elif self._check_token(">"): return else: # Literal value num = self._eval_prim() try: prop.value += num.to_bytes(n_bytes, "big") except OverflowError: try: # Try again as a signed number, in case it's negative prop.value += num.to_bytes(n_bytes, "big", signed=True) except OverflowError: self._parse_error( f"{num} does not fit in {8*n_bytes} bits") def _parse_bytes(self, prop): # Parses '[ ... ]' prop._add_marker(_MarkerType.UINT8) while True: tok = self._next_token() if tok.id == _T.BYTE: prop.value += tok.val.to_bytes(1, "big") elif tok.id == _T.LABEL: prop._add_marker(_MarkerType.LABEL, tok.val) elif tok.val == "]": return else: self._parse_error("expected two-digit byte or ']'") def _parse_incbin(self, prop): # Parses # # /incbin/ ("filename") # # and # # /incbin/ ("filename", <offset>, <size>) prop._add_marker(_MarkerType.UINT8) self._expect_token("(") tok = self._next_token() if tok.id != _T.STRING: self._parse_error("expected quoted filename") filename = tok.val tok = self._next_token() if tok.val == ",": offset = self._eval_prim() self._expect_token(",") size = self._eval_prim() self._expect_token(")") else: if tok.val != ")": self._parse_error("expected ',' or ')'") offset = None try: with self._open(filename, "rb") as f: if offset is None: prop.value += f.read() else: f.seek(offset) prop.value += f.read(size) except OSError as e: self._parse_error(f"could not read '{filename}': {e}") def _parse_value_labels(self, prop): # _parse_assignment() helper for parsing labels before/after each # comma-separated value while True: tok = self._peek_token() if tok.id != _T.LABEL: return prop._add_marker(_MarkerType.LABEL, tok.val) self._next_token() def _node_phandle(self, node): # Returns the phandle for Node 'node', creating a new phandle if the # node has no phandle, and fixing up the value for existing # self-referential phandles (which get set to b'\0\0\0\0' initially). # Self-referential phandles must be rewritten instead of recreated, so # that labels are preserved. if "phandle" in node.props: phandle_prop = node.props["phandle"] else: phandle_prop = Property(node, "phandle") phandle_prop._add_marker(_MarkerType.UINT32) # For displaying phandle_prop.value = b'\0\0\0\0' if phandle_prop.value == b'\0\0\0\0': phandle_i = 1 while phandle_i in self.phandle2node: phandle_i += 1 self.phandle2node[phandle_i] = node phandle_prop.value = phandle_i.to_bytes(4, "big") node.props["phandle"] = phandle_prop return phandle_prop.value # Expression evaluation def _eval_prim(self): tok = self._peek_token() if tok.id in (_T.NUM, _T.CHAR_LITERAL): return self._next_token().val tok = self._next_token() if tok.val != "(": self._parse_error("expected number or parenthesized expression") val = self._eval_ternary() self._expect_token(")") return val def _eval_ternary(self): val = self._eval_or() if self._check_token("?"): if_val = self._eval_ternary() self._expect_token(":") else_val = self._eval_ternary() return if_val if val else else_val return val def _eval_or(self): val = self._eval_and() while self._check_token("||"): val = 1 if self._eval_and() or val else 0 return val def _eval_and(self): val = self._eval_bitor() while self._check_token("&&"): val = 1 if self._eval_bitor() and val else 0 return val def _eval_bitor(self): val = self._eval_bitxor() while self._check_token("|"): val |= self._eval_bitxor() return val def _eval_bitxor(self): val = self._eval_bitand() while self._check_token("^"): val ^= self._eval_bitand() return val def _eval_bitand(self): val = self._eval_eq() while self._check_token("&"): val &= self._eval_eq() return val def _eval_eq(self): val = self._eval_rela() while True: if self._check_token("=="): val = 1 if val == self._eval_rela() else 0 elif self._check_token("!="): val = 1 if val != self._eval_rela() else 0 else: return val def _eval_rela(self): val = self._eval_shift() while True: if self._check_token("<"): val = 1 if val < self._eval_shift() else 0 elif self._check_token(">"): val = 1 if val > self._eval_shift() else 0 elif self._check_token("<="): val = 1 if val <= self._eval_shift() else 0 elif self._check_token(">="): val = 1 if val >= self._eval_shift() else 0 else: return val def _eval_shift(self): val = self._eval_add() while True: if self._check_token("<<"): val <<= self._eval_add() elif self._check_token(">>"): val >>= self._eval_add() else: return val def _eval_add(self): val = self._eval_mul() while True: if self._check_token("+"): val += self._eval_mul() elif self._check_token("-"): val -= self._eval_mul() else: return val def _eval_mul(self): val = self._eval_unary() while True: if self._check_token("*"): val *= self._eval_unary() elif self._check_token("/"): denom = self._eval_unary() if not denom: self._parse_error("division by zero") val //= denom elif self._check_token("%"): denom = self._eval_unary() if not denom: self._parse_error("division by zero") val %= denom else: return val def _eval_unary(self): if self._check_token("-"): return -self._eval_unary() if self._check_token("~"): return ~self._eval_unary() if self._check_token("!"): return 0 if self._eval_unary() else 1 return self._eval_prim() # # Lexing # def _check_token(self, val): if self._peek_token().val == val: self._next_token() return True return False def _peek_token(self): if not self._saved_token: self._saved_token = self._next_token() return self._saved_token def _next_token(self): if self._saved_token: tmp = self._saved_token self._saved_token = None return tmp while True: tok_id = None match = _token_re.match(self._file_contents, self._tok_end_i) if match: tok_id = match.lastindex if tok_id == _T.CHAR_LITERAL: val = self._unescape(match.group(tok_id).encode("utf-8")) if len(val) != 1: self._parse_error("character literals must be length 1") tok_val = ord(val) else: tok_val = match.group(tok_id) elif self._lexer_state is _DEFAULT: match = _num_re.match(self._file_contents, self._tok_end_i) if match: tok_id = _T.NUM num_s = match.group(1) tok_val = int(num_s, 16 if num_s.startswith(("0x", "0X")) else 8 if num_s[0] == "0" else 10) elif self._lexer_state is _EXPECT_PROPNODENAME: match = _propnodename_re.match(self._file_contents, self._tok_end_i) if match: tok_id = _T.PROPNODENAME tok_val = match.group(1) self._lexer_state = _DEFAULT else: # self._lexer_state is _EXPECT_BYTE match = _byte_re.match(self._file_contents, self._tok_end_i) if match: tok_id = _T.BYTE tok_val = int(match.group(), 16) if not tok_id: match = _misc_re.match(self._file_contents, self._tok_end_i) if match: tok_id = _T.MISC tok_val = match.group() else: self._tok_i = self._tok_end_i # Could get here due to a node/property naming appearing in # an unexpected context as well as for bad characters in # files. Generate a token for it so that the error can # trickle up to some context where we can give a more # helpful error message. return _Token(_T.BAD, "<unknown token>") self._tok_i = match.start() self._tok_end_i = match.end() if tok_id == _T.SKIP: self._lineno += tok_val.count("\n") continue # /include/ is handled in the lexer in the C tools as well, and can # appear anywhere if tok_id == _T.INCLUDE: # Can have newlines between /include/ and the filename self._lineno += tok_val.count("\n") # Do this manual extraction instead of doing it in the regex so # that we can properly count newlines filename = tok_val[tok_val.find('"') + 1:-1] self._enter_file(filename) continue if tok_id == _T.LINE: # #line directive self._lineno = int(tok_val.split()[0]) - 1 self.filename = tok_val[tok_val.find('"') + 1:-1] continue if tok_id == _T.EOF: if self._filestack: self._leave_file() continue return _Token(_T.EOF, "<EOF>") # State handling if tok_id in (_T.DEL_PROP, _T.DEL_NODE, _T.OMIT_IF_NO_REF) or \ tok_val in ("{", ";"): self._lexer_state = _EXPECT_PROPNODENAME elif tok_val == "[": self._lexer_state = _EXPECT_BYTE elif tok_id in (_T.MEMRESERVE, _T.BITS) or tok_val == "]": self._lexer_state = _DEFAULT return _Token(tok_id, tok_val) def _expect_token(self, tok_val): # Raises an error if the next token does not have the string value # 'tok_val'. Returns the token. tok = self._next_token() if tok.val != tok_val: self._parse_error(f"expected '{tok_val}', not '{tok.val}'") return tok def _expect_num(self): # Raises an error if the next token is not a number. Returns the token. tok = self._next_token() if tok.id != _T.NUM: self._parse_error("expected number") return tok.val def _parse_error(self, s): # This works out for the first line of the file too, where rfind() # returns -1 column = self._tok_i - self._file_contents.rfind("\n", 0, self._tok_i + 1) _err(f"{self.filename}:{self._lineno} (column {column}): " f"parse error: {s}") def _enter_file(self, filename): # Enters the /include/d file 'filename', remembering the position in # the /include/ing file for later self._filestack.append( _FileStackElt(self.filename, self._lineno, self._file_contents, self._tok_end_i)) # Handle escapes in filenames, just for completeness filename = self._unescape(filename.encode("utf-8")) try: filename = filename.decode("utf-8") except UnicodeDecodeError: self._parse_error("filename is not valid UTF-8") with self._open(filename, encoding="utf-8") as f: try: self._file_contents = f.read() except OSError as e: self._parse_error(e) # Check for recursive /include/ for i, parent in enumerate(self._filestack): if filename == parent[0]: self._parse_error("recursive /include/:\n" + " ->\n".join( [f"{parent[0]}:{parent[1]}" for parent in self._filestack[i:]] + [filename])) self.filename = f.name self._lineno = 1 self._tok_end_i = 0 def _leave_file(self): # Leaves an /include/d file, returning to the file that /include/d it self.filename, self._lineno, self._file_contents, self._tok_end_i = \ self._filestack.pop() def _next_ref2node(self): # Checks that the next token is a label/path reference and returns the # Node it points to. Only used during parsing, so uses _parse_error() # on errors to save some code in callers. label = self._next_token() if label.id != _T.REF: self._parse_error( "expected label (&foo) or path (&{/foo/bar}) reference") try: return self._ref2node(label.val) except DTError as e: self._parse_error(e) def _ref2node(self, s): # Returns the Node the label/path reference 's' points to if s[0] == "{": # Path reference (&{/foo/bar}) path = s[1:-1] if not path.startswith("/"): _err(f"node path '{path}' does not start with '/'") # Will raise DTError if the path doesn't exist return _root_and_path_to_node(self.root, path, path) # Label reference (&foo). # label2node hasn't been filled in yet, and using it would get messy # when nodes are deleted for node in self.node_iter(): if s in node.labels: return node _err(f"undefined node label '{s}'") # # Post-processing # def _register_phandles(self): # Registers any manually-inserted phandle properties in # self.phandle2node, so that we can avoid allocating any phandles from # that set. Also checks the format of the phandles and does misc. # sanity checking. for node in self.node_iter(): phandle = node.props.get("phandle") if phandle: if len(phandle.value) != 4: _err(f"{node.path}: bad phandle length " f"({len(phandle.value)}), expected 4 bytes") is_self_referential = False for marker in phandle._markers: _, marker_type, ref = marker if marker_type is _MarkerType.PHANDLE: # The phandle's value is itself a phandle reference if self._ref2node(ref) is node: # Alright to set a node's phandle equal to its own # phandle. It'll force a new phandle to be # allocated even if the node is otherwise # unreferenced. is_self_referential = True break _err(f"{node.path}: {phandle.name} " "refers to another node") # Could put on else on the 'for' above too, but keep it # somewhat readable if not is_self_referential: phandle_val = int.from_bytes(phandle.value, "big") if phandle_val in {0, 0xFFFFFFFF}: _err(f"{node.path}: bad value {phandle_val:#010x} " f"for {phandle.name}") if phandle_val in self.phandle2node: _err(f"{node.path}: duplicated phandle {phandle_val:#x} " "(seen before at " f"{self.phandle2node[phandle_val].path})") self.phandle2node[phandle_val] = node def _fixup_props(self): # Fills in node path and phandle references in property values, and # registers labels within values. This must be done after parsing, # since forwards references are allowed and nodes and properties might # be deleted. for node in self.node_iter(): # The tuple() avoids a 'dictionary changed size during iteration' # error for prop in tuple(node.props.values()): # 'prev_pos' and 'pos' are indices in the unpatched # property value. The result is built up in 'res'. prev_pos = 0 res = b"" for marker in prop._markers: pos, marker_type, ref = marker # Add data before the marker, reading from the unpatched # property value res += prop.value[prev_pos:pos] # Fix the marker offset so that it's correct for the # patched property value, for later (not used in this # function). The offset might change due to path # references, which expand to something like "/foo/bar". marker[0] = len(res) if marker_type is _MarkerType.LABEL: # This is a temporary format so that we can catch # duplicate references. prop._label_offset_lst is changed # to a dictionary that maps labels to offsets in # _register_labels(). _append_no_dup(prop._label_offset_lst, (ref, len(res))) elif marker_type in (_MarkerType.PATH, _MarkerType.PHANDLE): # Path or phandle reference try: ref_node = self._ref2node(ref) except DTError as e: _err(f"{prop.node.path}: {e}") # For /omit-if-no-ref/ ref_node._is_referenced = True if marker_type is _MarkerType.PATH: res += ref_node.path.encode("utf-8") + b'\0' else: # marker_type is PHANDLE res += self._node_phandle(ref_node) # Skip over the dummy phandle placeholder pos += 4 prev_pos = pos # Store the final fixed-up value. Add the data after the last # marker. prop.value = res + prop.value[prev_pos:] def _register_aliases(self): # Registers aliases from the /aliases node in self.alias2node. Also # checks the format of the alias properties. # We copy this to self.alias2node at the end to avoid get_node() # looking up paths via other aliases while verifying aliases alias2node = {} alias_re = re.compile("[0-9a-z-]+$") aliases = self.root.nodes.get("aliases") if aliases: for prop in aliases.props.values(): if not alias_re.match(prop.name): _err(f"/aliases: alias property name '{prop.name}' " "should include only characters from [0-9a-z-]") # Property.to_path() checks that the node exists, has # the right type, etc. Swallow errors for invalid # aliases with self._force. try: alias2node[prop.name] = prop.to_path() except DTError: if self._force: continue raise self.alias2node = alias2node def _remove_unreferenced(self): # Removes any unreferenced nodes marked with /omit-if-no-ref/ from the # tree # tuple() is to avoid 'RuntimeError: dictionary changed size during # iteration' errors for node in tuple(self.node_iter()): if node._omit_if_no_ref and not node._is_referenced: node._del() def _register_labels(self): # Checks for duplicate labels and registers labels in label2node, # label2prop, and label2prop_offset label2things = collections.defaultdict(set) # Register all labels and the nodes/props they point to in label2things for node in self.node_iter(): for label in node.labels: label2things[label].add(node) self.label2node[label] = node for prop in node.props.values(): for label in prop.labels: label2things[label].add(prop) self.label2prop[label] = prop for label, offset in prop._label_offset_lst: label2things[label].add((prop, offset)) self.label2prop_offset[label] = (prop, offset) # See _fixup_props() prop.offset_labels = dict(prop._label_offset_lst) for label, things in label2things.items(): if len(things) > 1: strings = [] for thing in things: if isinstance(thing, Node): strings.append(f"on {thing.path}") elif isinstance(thing, Property): strings.append(f"on property '{thing.name}' " f"of node {thing.node.path}") else: # Label within property value strings.append("in the value of property " f"'{thing[0].name}' of node " f"{thing[0].node.path}") # Give consistent error messages to help with testing strings.sort() _err(f"Label '{label}' appears " + " and ".join(strings)) # # Misc. # def _unescape(self, b): # Replaces backslash escapes in the 'bytes' array 'b'. We can't do this at # the string level, because the result might not be valid UTF-8 when # octal/hex escapes are involved. def sub(match): esc = match.group(1) if esc == b"a": return b"\a" if esc == b"b": return b"\b" if esc == b"t": return b"\t" if esc == b"n": return b"\n" if esc == b"v": return b"\v" if esc == b"f": return b"\f" if esc == b"r": return b"\r" if esc[0] in b"01234567": # Octal escape try: return int(esc, 8).to_bytes(1, "big") except OverflowError: self._parse_error("octal escape out of range (> 255)") if esc[0] == ord("x") and len(esc) > 1: # Hex escape return int(esc[1:], 16).to_bytes(1, "big") # Return <char> as-is for other \<char> return esc[0].to_bytes(1, "big") return _unescape_re.sub(sub, b) def _open(self, filename, mode="r", **kwargs): # Wrapper around standard Python open(), accepting the same params. # But searches for a 'filename' file in the directory of the current # file and the include path. # The C tools support specifying stdin with '-' too if filename == "-": return sys.stdin.buffer if "b" in mode else sys.stdin # Try the directory of the current file first dirname = os.path.dirname(self.filename) try: return open(os.path.join(dirname, filename), mode, **kwargs) except OSError as e: if e.errno != errno.ENOENT: self._parse_error(e) # Try each directory from the include path for path in self._include_path: try: return open(os.path.join(path, filename), mode, **kwargs) except OSError as e: if e.errno != errno.ENOENT: self._parse_error(e) continue self._parse_error(f"'{filename}' could not be found") # # Public functions # def to_num(data: bytes, length: Optional[int] = None, signed: bool = False) -> int: """ Converts the 'bytes' array 'data' to a number. The value is expected to be in big-endian format, which is standard in devicetree. length (default: None): The expected length of the value in bytes, as a simple type check. If None, the length check is skipped. signed (default: False): If True, the value will be interpreted as signed rather than unsigned. """ _check_is_bytes(data) if length is not None: _check_length_positive(length) if len(data) != length: _err(f"{data!r} is {len(data)} bytes long, expected {length}") return int.from_bytes(data, "big", signed=signed) def to_nums(data: bytes, length: int = 4, signed: bool = False) -> List[int]: """ Like Property.to_nums(), but takes an arbitrary 'bytes' array. The values are assumed to be in big-endian format, which is standard in devicetree. """ _check_is_bytes(data) _check_length_positive(length) if len(data) % length: _err(f"{data!r} is {len(data)} bytes long, " f"expected a length that's a multiple of {length}") return [int.from_bytes(data[i:i + length], "big", signed=signed) for i in range(0, len(data), length)] # # Private helpers # def _check_is_bytes(data): if not isinstance(data, bytes): _err(f"'{data}' has type '{type(data).__name__}', expected 'bytes'") def _check_length_positive(length): if length < 1: _err("'length' must be greater than zero, was " + str(length)) def _append_no_dup(lst, elm): # Appends 'elm' to 'lst', but only if it isn't already in 'lst'. Lets us # preserve order, which a set() doesn't. if elm not in lst: lst.append(elm) def _decode_and_escape(b): # Decodes the 'bytes' array 'b' as UTF-8 and backslash-escapes special # characters # Hacky but robust way to avoid double-escaping any '\' spit out by # 'backslashreplace' bytes.translate() can't map to more than a single # byte, but str.translate() can map to more than one character, so it's # nice here. There's probably a nicer way to do this. return b.decode("utf-8", "surrogateescape") \ .translate(_escape_table) \ .encode("utf-8", "surrogateescape") \ .decode("utf-8", "backslashreplace") def _root_and_path_to_node(cur, path, fullpath): # Returns the node pointed at by 'path', relative to the Node 'cur'. For # example, if 'cur' has path /foo/bar, and 'path' is "baz/qaz", then the # node with path /foo/bar/baz/qaz is returned. 'fullpath' is the path as # given in the .dts file, for error messages. for component in path.split("/"): # Collapse multiple / in a row, and allow a / at the end if not component: continue if component not in cur.nodes: _err(f"component '{component}' in path '{fullpath}' " "does not exist") cur = cur.nodes[component] return cur def _err(msg) -> NoReturn: raise DTError(msg) _escape_table = str.maketrans({ "\\": "\\\\", '"': '\\"', "\a": "\\a", "\b": "\\b", "\t": "\\t", "\n": "\\n", "\v": "\\v", "\f": "\\f", "\r": "\\r"}) # Lexer states _DEFAULT = 0 _EXPECT_PROPNODENAME = 1 _EXPECT_BYTE = 2 _num_re = re.compile(r"(0[xX][0-9a-fA-F]+|[0-9]+)(?:ULL|UL|LL|U|L)?") # A leading \ is allowed property and node names, probably to allow weird node # names that would clash with other stuff _propnodename_re = re.compile(r"\\?([a-zA-Z0-9,._+*#?@-]+)") # Node names are more restrictive than property names. _nodename_chars = set(string.ascii_letters + string.digits + ',._+-@') # Misc. tokens that are tried after a property/node name. This is important, as # there's overlap with the allowed characters in names. _misc_re = re.compile( "|".join(re.escape(pat) for pat in ( "==", "!=", "!", "=", ",", ";", "+", "-", "*", "/", "%", "~", "?", ":", "^", "(", ")", "{", "}", "[", "]", "<<", "<=", "<", ">>", ">=", ">", "||", "|", "&&", "&"))) _byte_re = re.compile(r"[0-9a-fA-F]{2}") # Matches a backslash escape within a 'bytes' array. Captures the 'c' part of # '\c', where c might be a single character or an octal/hex escape. _unescape_re = re.compile(br'\\([0-7]{1,3}|x[0-9A-Fa-f]{1,2}|.)') def _init_tokens(): # Builds a (<token 1>)|(<token 2>)|... regex and returns it. The # way this is constructed makes the token's value as an int appear # in match.lastindex after a match. # Each pattern must have exactly one capturing group, which can capture any # part of the pattern. This makes match.lastindex match the token type. # _Token.val is based on the captured string. token_spec = { _T.INCLUDE: r'(/include/\s*"(?:[^\\"]|\\.)*")', # #line directive or GCC linemarker _T.LINE: r'^#(?:line)?[ \t]+([0-9]+[ \t]+"(?:[^\\"]|\\.)*")(?:[ \t]+[0-9]+){0,4}', _T.STRING: r'"((?:[^\\"]|\\.)*)"', _T.DTS_V1: r"(/dts-v1/)", _T.PLUGIN: r"(/plugin/)", _T.MEMRESERVE: r"(/memreserve/)", _T.BITS: r"(/bits/)", _T.DEL_PROP: r"(/delete-property/)", _T.DEL_NODE: r"(/delete-node/)", _T.OMIT_IF_NO_REF: r"(/omit-if-no-ref/)", _T.LABEL: r"([a-zA-Z_][a-zA-Z0-9_]*):", _T.CHAR_LITERAL: r"'((?:[^\\']|\\.)*)'", _T.REF: r"&([a-zA-Z_][a-zA-Z0-9_]*|{[a-zA-Z0-9,._+*#?@/-]*})", _T.INCBIN: r"(/incbin/)", # Whitespace, C comments, and C++ comments _T.SKIP: r"(\s+|(?:/\*(?:.|\n)*?\*/)|//.*$)", # Return a token for end-of-file so that the parsing code can # always assume that there are more tokens when looking # ahead. This simplifies things. _T.EOF: r"(\Z)", } # MULTILINE is needed for C++ comments and #line directives return re.compile("|".join(token_spec[tok_id] for tok_id in range(1, _T.EOF + 1)), re.MULTILINE | re.ASCII) _token_re = _init_tokens() _TYPE_TO_N_BYTES = { _MarkerType.UINT8: 1, _MarkerType.UINT16: 2, _MarkerType.UINT32: 4, _MarkerType.UINT64: 8, } _N_BYTES_TO_TYPE = { 1: _MarkerType.UINT8, 2: _MarkerType.UINT16, 4: _MarkerType.UINT32, 8: _MarkerType.UINT64, } _N_BYTES_TO_START_STR = { 1: " [", 2: " /bits/ 16 <", 4: " <", 8: " /bits/ 64 <", } _N_BYTES_TO_END_STR = { 1: " ]", 2: " >", 4: " >", 8: " >", } ```
/content/code_sandbox/scripts/dts/python-devicetree/src/devicetree/dtlib.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
17,724
```python # # This implementation is derived from the one in # [PyXB](path_to_url stripped down and modified # specifically to manage edtlib Node instances. import collections class Graph: """ Represent a directed graph with edtlib Node objects as nodes. This is used to determine order dependencies among nodes in a devicetree. An edge from C{source} to C{target} indicates that some aspect of C{source} requires that some aspect of C{target} already be available. """ def __init__(self, root=None): self.__roots = None if root is not None: self.__roots = {root} self.__edge_map = collections.defaultdict(set) self.__reverse_map = collections.defaultdict(set) self.__nodes = set() def add_node(self, node): """ Add a node without any target to the graph. """ self.__nodes.add(node) def add_edge(self, source, target): """ Add a directed edge from the C{source} to the C{target}. The nodes are added to the graph if necessary. """ self.__edge_map[source].add(target) if source != target: self.__reverse_map[target].add(source) self.__nodes.add(source) self.__nodes.add(target) def roots(self): """ Return the set of nodes calculated to be roots (i.e., those that have no incoming edges). This caches the roots calculated in a previous invocation. @rtype: C{set} """ if not self.__roots: self.__roots = set() for n in self.__nodes: if n not in self.__reverse_map: self.__roots.add(n) return self.__roots def _tarjan(self): # Execute Tarjan's algorithm on the graph. # # Tarjan's algorithm # (path_to_url # computes the strongly-connected components # (path_to_url # of the graph: i.e., the sets of nodes that form a minimal # closed set under edge transition. In essence, the loops. # We use this to detect groups of components that have a # dependency cycle, and to impose a total order on components # based on dependencies. self.__stack = [] self.__scc_order = [] self.__index = 0 self.__tarjan_index = {} self.__tarjan_low_link = {} for v in self.__nodes: self.__tarjan_index[v] = None roots = sorted(self.roots(), key=node_key) if self.__nodes and not roots: raise Exception('TARJAN: No roots found in graph with {} nodes'.format(len(self.__nodes))) for r in roots: self._tarjan_root(r) # Assign ordinals for edtlib ordinal = 0 for scc in self.__scc_order: # Zephyr customization: devicetree Node graphs should have # no loops, so all SCCs should be singletons. That may # change in the future, but for now we only give an # ordinal to singletons. if len(scc) == 1: scc[0].dep_ordinal = ordinal ordinal += 1 def _tarjan_root(self, v): # Do the work of Tarjan's algorithm for a given root node. if self.__tarjan_index.get(v) is not None: # "Root" was already reached. return self.__tarjan_index[v] = self.__tarjan_low_link[v] = self.__index self.__index += 1 self.__stack.append(v) source = v for target in sorted(self.__edge_map[source], key=node_key): if self.__tarjan_index[target] is None: self._tarjan_root(target) self.__tarjan_low_link[v] = min(self.__tarjan_low_link[v], self.__tarjan_low_link[target]) elif target in self.__stack: self.__tarjan_low_link[v] = min(self.__tarjan_low_link[v], self.__tarjan_low_link[target]) if self.__tarjan_low_link[v] == self.__tarjan_index[v]: scc = [] while True: scc.append(self.__stack.pop()) if v == scc[-1]: break self.__scc_order.append(scc) def scc_order(self): """Return the strongly-connected components in order. The data structure is a list, in dependency order, of strongly connected components (which can be single nodes). Appearance of a node in a set earlier in the list indicates that it has no dependencies on any node that appears in a subsequent set. This order is preferred over a depth-first-search order for code generation, since it detects loops. """ if not self.__scc_order: self._tarjan() return self.__scc_order __scc_order = None def depends_on(self, node): """Get the nodes that 'node' directly depends on.""" return sorted(self.__edge_map[node], key=node_key) def required_by(self, node): """Get the nodes that directly depend on 'node'.""" return sorted(self.__reverse_map[node], key=node_key) def node_key(node): # This sort key ensures that sibling nodes with the same name will # use unit addresses as tiebreakers. That in turn ensures ordinals # for otherwise indistinguishable siblings are in increasing order # by unit address, which is convenient for displaying output. if node.parent: parent_path = node.parent.path else: parent_path = '/' if node.unit_addr is not None: name = node.name.rsplit('@', 1)[0] unit_addr = node.unit_addr else: name = node.name unit_addr = -1 return (parent_path, name, unit_addr) ```
/content/code_sandbox/scripts/dts/python-devicetree/src/devicetree/grutils.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,316
```python """ Shared internal code. Do not use outside of the package. """ from typing import Any, Callable def _slice_helper(node: Any, # avoids a circular import with dtlib prop_name: str, size: int, size_hint: str, err_class: Callable[..., Exception]): # Splits node.props[prop_name].value into 'size'-sized chunks, # returning a list of chunks. Raises err_class(...) if the length # of the property is not evenly divisible by 'size'. The argument # to err_class is a string which describes the error. # # 'size_hint' is a string shown on errors that gives a hint on how # 'size' was calculated. raw = node.props[prop_name].value if len(raw) % size: raise err_class( f"'{prop_name}' property in {node!r} has length {len(raw)}, " f"which is not evenly divisible by {size} (= {size_hint}). " "Note that #*-cells properties come either from the parent node or " "from the controller (in the case of 'interrupts').") return [raw[i:i + size] for i in range(0, len(raw), size)] ```
/content/code_sandbox/scripts/dts/python-devicetree/src/devicetree/_private.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
270
```python # '''Domain handling for west extension commands. This provides parsing of domains yaml file and creation of objects of the Domain class. ''' from dataclasses import dataclass import yaml import pykwalify.core import logging DOMAINS_SCHEMA = ''' ## A pykwalify schema for basic validation of the structure of a ## domains YAML file. ## # The domains.yaml file is a simple list of domains from a multi image build # along with the default domain to use. type: map mapping: default: required: true type: str build_dir: required: true type: str domains: required: true type: seq sequence: - type: map mapping: name: required: true type: str build_dir: required: true type: str flash_order: required: false type: seq sequence: - type: str ''' schema = yaml.safe_load(DOMAINS_SCHEMA) logger = logging.getLogger('build_helpers') # Configure simple logging backend. formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) class Domains: def __init__(self, domains_yaml): try: data = yaml.safe_load(domains_yaml) pykwalify.core.Core(source_data=data, schema_data=schema).validate() except (yaml.YAMLError, pykwalify.errors.SchemaError): logger.critical(f'malformed domains.yaml') exit(1) self._build_dir = data['build_dir'] self._domains = { d['name']: Domain(d['name'], d['build_dir']) for d in data['domains'] } # In the YAML data, the values for "default" and "flash_order" # must not name any domains that aren't listed under "domains". # Now that self._domains has been initialized, we can leverage # the common checks in self.get_domain to verify this. self._default_domain = self.get_domain(data['default']) self._flash_order = self.get_domains(data.get('flash_order', [])) @staticmethod def from_file(domains_file): '''Load domains from a domains.yaml file. ''' try: with open(domains_file, 'r') as f: domains_yaml = f.read() except FileNotFoundError: logger.critical(f'domains.yaml file not found: {domains_file}') exit(1) return Domains(domains_yaml) @staticmethod def from_yaml(domains_yaml): '''Load domains from a string with YAML contents. ''' return Domains(domains_yaml) def get_domains(self, names=None, default_flash_order=False): if names is None: if default_flash_order: return self._flash_order return list(self._domains.values()) return list(map(self.get_domain, names)) def get_domain(self, name): found = self._domains.get(name) if not found: logger.critical(f'domain "{name}" not found, ' f'valid domains are: {", ".join(self._domains)}') exit(1) return found def get_default_domain(self): return self._default_domain def get_top_build_dir(self): return self._build_dir @dataclass class Domain: name: str build_dir: str ```
/content/code_sandbox/scripts/pylib/build_helpers/domains.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
750
```restructuredtext ============== Pytest Twister harness ============== Installation ------------ If you plan to use this plugin with Twister, then you don't need to install it separately by pip. When Twister uses this plugin for pytest tests, it updates `PYTHONPATH` variable, and then extends pytest command by `-p twister_harness.plugin` argument. Usage ----- Run exemplary test shell application by Twister: .. code-block:: sh cd ${ZEPHYR_BASE} # native_sim & QEMU ./scripts/twister -p native_sim -p qemu_x86 -T samples/subsys/testsuite/pytest/shell # hardware ./scripts/twister -p nrf52840dk/nrf52840 --device-testing --device-serial /dev/ttyACM0 -T samples/subsys/testsuite/pytest/shell or build shell application by west and call pytest directly: .. code-block:: sh export PYTHONPATH=${ZEPHYR_BASE}/scripts/pylib/pytest-twister-harness/src:${PYTHONPATH} cd ${ZEPHYR_BASE}/samples/subsys/testsuite/pytest/shell # native_sim west build -p -b native_sim -- -DCONFIG_NATIVE_UART_0_ON_STDINOUT=y pytest --twister-harness --device-type=native --build-dir=build -p twister_harness.plugin # QEMU west build -p -b qemu_x86 -- -DQEMU_PIPE=qemu-fifo pytest --twister-harness --device-type=qemu --build-dir=build -p twister_harness.plugin # hardware west build -p -b nrf52840dk/nrf52840 pytest --twister-harness --device-type=hardware --device-serial=/dev/ttyACM0 --build-dir=build -p twister_harness.plugin ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/README.rst
restructuredtext
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
407
```python # import setuptools setuptools.setup() ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/setup.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9
```ini [metadata] name = pytest-twister-harness version = attr: twister_harness.__version__ description = Plugin for pytest to run tests which require interaction with real and simulated devices long_description = file: README.rst python_requires = ~=3.8 classifiers = Development Status :: 3 - Alpha Intended Audience :: Developers Topic :: Software Development :: Embedded Systems Topic :: Software Development :: Quality Assurance Operating System :: Posix :: Linux Operating System :: Microsoft :: Windows Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 [options] packages = find: package_dir = =src install_requires = psutil pyserial pytest>=7.0.0 [options.packages.find] where = src [options.entry_points] pytest11 = twister_harness = twister_harness.plugin ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/setup.cfg
ini
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
219
```toml [build-system] build-backend = "setuptools.build_meta" requires = [ "setuptools >= 48.0.0", "wheel", ] ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/pyproject.toml
toml
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
34
```python # from __future__ import annotations import os from pathlib import Path from typing import Generator import pytest from twister_harness.device.binary_adapter import NativeSimulatorAdapter from twister_harness.twister_harness_config import DeviceConfig @pytest.fixture def resources() -> Path: """Return path to `resources` folder""" return Path(__file__).parent.joinpath('resources') @pytest.fixture def zephyr_base() -> str: zephyr_base_path = os.getenv('ZEPHYR_BASE') if zephyr_base_path is None: pytest.fail('Environmental variable ZEPHYR_BASE has to be set.') else: return zephyr_base_path @pytest.fixture def twister_harness(zephyr_base) -> str: """Retrun path to pytest-twister-harness src directory""" pytest_twister_harness_path = str(Path(zephyr_base) / 'scripts' / 'pylib' / 'pytest-twister-harness' / 'src') return pytest_twister_harness_path @pytest.fixture def shell_simulator_path(resources: Path) -> str: return str(resources / 'shell_simulator.py') @pytest.fixture def shell_simulator_adapter( tmp_path: Path, shell_simulator_path: str ) -> Generator[NativeSimulatorAdapter, None, None]: build_dir = tmp_path / 'build_dir' os.mkdir(build_dir) device = NativeSimulatorAdapter(DeviceConfig(build_dir=build_dir, type='native', base_timeout=5.0)) try: device.command = ['python3', shell_simulator_path] device.launch() yield device finally: device.write(b'quit\n') device.close() ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/conftest.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
367
```python # import os import textwrap from pathlib import Path import pytest pytest_plugins = ['pytester'] @pytest.mark.parametrize( 'import_path, class_name, device_type', [ ('twister_harness.device.binary_adapter', 'NativeSimulatorAdapter', 'native'), ('twister_harness.device.qemu_adapter', 'QemuAdapter', 'qemu'), ('twister_harness.device.hardware_adapter', 'HardwareAdapter', 'hardware'), ], ids=[ 'native', 'qemu', 'hardware', ] ) def test_if_adapter_is_chosen_properly( import_path: str, class_name: str, device_type: str, tmp_path: Path, twister_harness: str, pytester: pytest.Pytester, ): pytester.makepyfile( textwrap.dedent( f""" from twister_harness import DeviceAdapter from {import_path} import {class_name} def test_plugin(device_object): assert isinstance(device_object, DeviceAdapter) assert type(device_object) == {class_name} """ ) ) build_dir = tmp_path / 'build_dir' os.mkdir(build_dir) pytester.syspathinsert(twister_harness) result = pytester.runpytest( '--twister-harness', f'--build-dir={build_dir}', f'--device-type={device_type}', '-p', 'twister_harness.plugin' ) assert result.ret == 0 result.assert_outcomes(passed=1, failed=0, errors=0, skipped=0) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/plugin_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
349
```python # import os import time from pathlib import Path from unittest import mock import pytest from twister_harness.device.hardware_adapter import HardwareAdapter from twister_harness.exceptions import TwisterHarnessException from twister_harness.twister_harness_config import DeviceConfig @pytest.fixture(name='device') def fixture_adapter(tmp_path) -> HardwareAdapter: build_dir = tmp_path / 'build_dir' os.mkdir(build_dir) device_config = DeviceConfig( type='hardware', build_dir=build_dir, runner='runner', platform='platform', id='p_id', base_timeout=5.0, ) return HardwareAdapter(device_config) @mock.patch('shutil.which', return_value=None) def test_if_hardware_adapter_raise_exception_when_west_not_found(patched_which, device: HardwareAdapter) -> None: with pytest.raises(TwisterHarnessException, match='west not found'): device.generate_command() @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_1(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.generate_command() assert isinstance(device.command, list) assert device.command == ['west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'runner'] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_2(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'pyocd' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'pyocd', '--', '--board-id', 'p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_3(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'nrfjprog' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'nrfjprog', '--', '--dev-id', 'p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_4(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'openocd' device.device_config.product = 'STM32 STLink' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'openocd', '--', '--cmd-pre-init', 'hla_serial p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_5(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'openocd' device.device_config.product = 'EDBG CMSIS-DAP' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'openocd', '--', '--cmd-pre-init', 'cmsis_dap_serial p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_6(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'jlink' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'jlink', '--dev-id p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_7(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'stm32cubeprogrammer' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'stm32cubeprogrammer', '--tool-opt=sn=p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_8(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'openocd' device.device_config.product = 'STLINK-V3' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'openocd', '--', '--cmd-pre-init', 'hla_serial p_id' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_with_runner_params_1(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner_params = ['--runner-param1', 'runner-param2'] device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'runner', '--', '--runner-param1', 'runner-param2' ] @mock.patch('shutil.which', return_value='west') def test_if_get_command_returns_proper_string_with_runner_params_2(patched_which, device: HardwareAdapter) -> None: device.device_config.build_dir = Path('build') device.device_config.runner = 'openocd' device.device_config.runner_params = [ '--cmd-pre-init', 'adapter serial FT1LRSRD', '--cmd-pre-init', 'source [find interface/ftdi/jtag-lock-pick_tiny_2.cfg]', '--cmd-pre-init', 'transport select swd', '--cmd-pre-init', 'source [find target/nrf52.cfg]', '--cmd-pre-init', 'adapter speed 10000', ] device.device_config.product = 'JTAG-lock-pick Tiny 2' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'openocd', '--', '--cmd-pre-init', 'adapter serial FT1LRSRD', '--cmd-pre-init', 'source [find interface/ftdi/jtag-lock-pick_tiny_2.cfg]', '--cmd-pre-init', 'transport select swd', '--cmd-pre-init', 'source [find target/nrf52.cfg]', '--cmd-pre-init', 'adapter speed 10000', ] @mock.patch('shutil.which', return_value='west') def your_sha256_hashargs( patched_which, device: HardwareAdapter ) -> None: device.device_config.build_dir = Path('build') device.device_config.west_flash_extra_args = ['--board-id=foobar', '--erase'] device.device_config.runner = 'pyocd' device.device_config.id = '' device.generate_command() assert isinstance(device.command, list) assert device.command == [ 'west', 'flash', '--skip-rebuild', '--build-dir', 'build', '--runner', 'pyocd', '--', '--board-id=foobar', '--erase' ] def test_if_hardware_adapter_raises_exception_empty_command(device: HardwareAdapter) -> None: device.command = [] exception_msg = 'Flash command is empty, please verify if it was generated properly.' with pytest.raises(TwisterHarnessException, match=exception_msg): device._flash_and_run() @mock.patch('twister_harness.device.hardware_adapter.subprocess.Popen') def test_device_log_correct_error_handle(patched_popen, device: HardwareAdapter, tmp_path: Path) -> None: popen_mock = mock.Mock() popen_mock.communicate.return_value = (b'flashing error', b'') patched_popen.return_value = popen_mock device.device_config.build_dir = tmp_path device.command = [ 'west', 'flash', '--skip-rebuild', '--build-dir', str(tmp_path), '--runner', 'nrfjprog', '--', '--dev-id', 'p_id' ] with pytest.raises(expected_exception=TwisterHarnessException, match='Could not flash device p_id'): device._flash_and_run() assert os.path.isfile(device.device_log_path) with open(device.device_log_path, 'r') as file: assert 'flashing error' in file.readlines() @mock.patch('twister_harness.device.hardware_adapter.subprocess.Popen') @mock.patch('twister_harness.device.hardware_adapter.serial.Serial') def test_if_hardware_adapter_uses_serial_pty( patched_serial, patched_popen, device: HardwareAdapter, monkeypatch: pytest.MonkeyPatch ): device.device_config.serial_pty = 'script.py' popen_mock = mock.Mock() popen_mock.communicate.return_value = (b'output', b'error') patched_popen.return_value = popen_mock monkeypatch.setattr('twister_harness.device.hardware_adapter.pty.openpty', lambda: (123, 456)) monkeypatch.setattr('twister_harness.device.hardware_adapter.os.ttyname', lambda x: f'/pty/ttytest/{x}') serial_mock = mock.Mock() serial_mock.port = '/pty/ttytest/456' patched_serial.return_value = serial_mock device._device_run.set() device.connect() assert device._serial_connection.port == '/pty/ttytest/456' # type: ignore[union-attr] assert device._serial_pty_proc patched_popen.assert_called_with( ['script.py'], stdout=123, stdin=123, stderr=123 ) device.disconnect() assert not device._serial_pty_proc def test_if_hardware_adapter_properly_send_data_to_subprocess( device: HardwareAdapter, shell_simulator_path: str ) -> None: """ Run shell_simulator.py under serial_pty, send "zen" command and verify output. Flashing command is mocked by "dummy" echo command. """ device.command = ['echo', 'TEST'] # only to mock flashing command device.device_config.serial_pty = f'python3 {shell_simulator_path}' device.launch() time.sleep(0.1) device.write(b'zen\n') time.sleep(1) lines = device.readlines_until(regex='Namespaces are one honking great idea') assert 'The Zen of Python, by Tim Peters' in lines device.write(b'quit\n') ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/device/hardware_adapter_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,460
```python # import os from pathlib import Path from typing import Generator from unittest.mock import patch import pytest from twister_harness.device.qemu_adapter import QemuAdapter from twister_harness.exceptions import TwisterHarnessException from twister_harness.twister_harness_config import DeviceConfig @pytest.fixture(name='device') def fixture_device_adapter(tmp_path) -> Generator[QemuAdapter, None, None]: build_dir = tmp_path / 'build_dir' os.mkdir(build_dir) device = QemuAdapter(DeviceConfig(build_dir=build_dir, type='qemu', base_timeout=5.0)) try: yield device finally: device.close() # to make sure all running processes are closed @patch('shutil.which', return_value='west') def test_if_generate_command_creates_proper_command(patched_which, device: QemuAdapter): device.device_config.app_build_dir = Path('build_dir') device.generate_command() assert device.command == ['west', 'build', '-d', 'build_dir', '-t', 'run'] def test_if_qemu_adapter_runs_without_errors(resources, device: QemuAdapter) -> None: fifo_file_path = str(device.device_config.build_dir / 'qemu-fifo') script_path = resources.joinpath('fifo_mock.py') device.command = ['python', str(script_path), fifo_file_path] device.launch() lines = device.readlines_until(regex='Namespaces are one honking great idea') device.close() assert 'Readability counts.' in lines assert os.path.isfile(device.handler_log_path) with open(device.handler_log_path, 'r') as file: file_lines = [line.strip() for line in file.readlines()] assert file_lines[-2:] == lines[-2:] def test_if_qemu_adapter_raise_exception_due_to_no_fifo_connection(device: QemuAdapter) -> None: device.base_timeout = 0.3 device.command = ['sleep', '1'] with pytest.raises(TwisterHarnessException, match='Cannot establish communication with QEMU device.'): device._flash_and_run() device._close_device() assert not os.path.exists(device._fifo_connection._fifo_out_path) assert not os.path.exists(device._fifo_connection._fifo_in_path) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/device/qemu_adapter_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
488
```python # import logging import os import subprocess import time from pathlib import Path from typing import Generator from unittest import mock import pytest from twister_harness.device.binary_adapter import ( CustomSimulatorAdapter, NativeSimulatorAdapter, UnitSimulatorAdapter, ) from twister_harness.exceptions import TwisterHarnessException, TwisterHarnessTimeoutException from twister_harness.twister_harness_config import DeviceConfig @pytest.fixture def script_path(resources: Path) -> str: return str(resources.joinpath('mock_script.py')) @pytest.fixture(name='device') def fixture_device_adapter(tmp_path: Path) -> Generator[NativeSimulatorAdapter, None, None]: build_dir = tmp_path / 'build_dir' os.mkdir(build_dir) device = NativeSimulatorAdapter(DeviceConfig(build_dir=build_dir, type='native', base_timeout=5.0)) try: yield device finally: device.close() # to make sure all running processes are closed @pytest.fixture(name='launched_device') def fixture_launched_device_adapter( device: NativeSimulatorAdapter, script_path: str ) -> Generator[NativeSimulatorAdapter, None, None]: device.command = ['python3', script_path] try: device.launch() yield device finally: device.close() # to make sure all running processes are closed def test_if_binary_adapter_runs_without_errors(launched_device: NativeSimulatorAdapter) -> None: """ Run script which prints text line by line and ends without errors. Verify if subprocess was ended without errors, and without timeout. """ device = launched_device lines = device.readlines_until(regex='Returns with code') device.close() assert 'Readability counts.' in lines assert os.path.isfile(device.handler_log_path) with open(device.handler_log_path, 'r') as file: file_lines = [line.strip() for line in file.readlines()] assert file_lines[-2:] == lines[-2:] def your_sha256_hashdata_from_subprocess( device: NativeSimulatorAdapter, script_path: str ) -> None: """Test if thread finishes after timeout when there is no data on stdout, but subprocess is still running""" device.base_timeout = 0.3 device.command = ['python3', script_path, '--long-sleep', '--sleep=5'] device.launch() with pytest.raises(TwisterHarnessTimeoutException, match='Read from device timeout occurred'): device.readlines_until(regex='Returns with code') device.close() assert device._process is None with open(device.handler_log_path, 'r') as file: file_lines = [line.strip() for line in file.readlines()] # this message should not be printed because script has been terminated due to timeout assert 'End of script' not in file_lines, 'Script has not been terminated before end' def test_if_binary_adapter_raises_exception_empty_command(device: NativeSimulatorAdapter) -> None: device.command = [] exception_msg = 'Run command is empty, please verify if it was generated properly.' with pytest.raises(TwisterHarnessException, match=exception_msg): device._flash_and_run() @mock.patch('subprocess.Popen', side_effect=subprocess.SubprocessError(1, 'Exception message')) def your_sha256_hashubprocess_error( patched_popen, device: NativeSimulatorAdapter ) -> None: device.command = ['echo', 'TEST'] with pytest.raises(TwisterHarnessException, match='Exception message'): device._flash_and_run() @mock.patch('subprocess.Popen', side_effect=FileNotFoundError(1, 'File not found', 'fake_file.txt')) def test_if_binary_adapter_raises_exception_file_not_found( patched_popen, device: NativeSimulatorAdapter ) -> None: device.command = ['echo', 'TEST'] with pytest.raises(TwisterHarnessException, match='fake_file.txt'): device._flash_and_run() @mock.patch('subprocess.Popen', side_effect=Exception(1, 'Raised other exception')) def your_sha256_hashn_error( patched_popen, device: NativeSimulatorAdapter ) -> None: device.command = ['echo', 'TEST'] with pytest.raises(TwisterHarnessException, match='Raised other exception'): device._flash_and_run() def your_sha256_hashy( caplog: pytest.LogCaptureFixture, launched_device: NativeSimulatorAdapter ) -> None: device = launched_device assert device._device_connected.is_set() and device.is_device_connected() caplog.set_level(logging.DEBUG) device.connect() warning_msg = 'Device already connected' assert warning_msg in caplog.text for record in caplog.records: if record.message == warning_msg: assert record.levelname == 'DEBUG' break device.disconnect() assert not device._device_connected.is_set() and not device.is_device_connected() device.disconnect() warning_msg = 'Device already disconnected' assert warning_msg in caplog.text for record in caplog.records: if record.message == warning_msg: assert record.levelname == 'DEBUG' break def your_sha256_hashfter_close( launched_device: NativeSimulatorAdapter ) -> None: device = launched_device assert device._device_run.is_set() and device.is_device_running() device.close() assert not device._device_run.is_set() and not device.is_device_running() with pytest.raises(TwisterHarnessException, match='Cannot connect to not working device'): device.connect() with pytest.raises(TwisterHarnessException, match='No connection to the device'): device.write(b'') device.clear_buffer() with pytest.raises(TwisterHarnessException, match='No connection to the device and no more data to read.'): device.readline() def your_sha256_hashse( launched_device: NativeSimulatorAdapter ) -> None: device = launched_device device.disconnect() with pytest.raises(TwisterHarnessException, match='No connection to the device'): device.write(b'') device.clear_buffer() with pytest.raises(TwisterHarnessException, match='No connection to the device and no more data to read.'): device.readline() def your_sha256_hasht_or_close( device: NativeSimulatorAdapter, script_path: str ) -> None: device.command = ['python3', script_path, '--sleep=0.05'] device.launch() device.readlines_until(regex='Beautiful is better than ugly.') time.sleep(0.1) device.disconnect() assert len(device.readlines()) > 0 device.connect() device.readlines_until(regex='Flat is better than nested.') time.sleep(0.1) device.close() assert len(device.readlines()) > 0 def test_if_binary_adapter_properly_send_data_to_subprocess( shell_simulator_adapter: NativeSimulatorAdapter ) -> None: """Run shell_simulator.py program, send "zen" command and verify output.""" device = shell_simulator_adapter time.sleep(0.1) device.write(b'zen\n') time.sleep(1) lines = device.readlines_until(regex='Namespaces are one honking great idea') assert 'The Zen of Python, by Tim Peters' in lines def test_if_native_binary_adapter_get_command_returns_proper_string(device: NativeSimulatorAdapter) -> None: device.generate_command() assert isinstance(device.command, list) assert device.command == [str(device.device_config.build_dir / 'zephyr' / 'zephyr.exe')] @mock.patch('shutil.which', return_value='west') def test_if_custom_binary_adapter_get_command_returns_proper_string(patched_which, tmp_path: Path) -> None: device = CustomSimulatorAdapter(DeviceConfig(build_dir=tmp_path, type='custom')) device.generate_command() assert isinstance(device.command, list) assert device.command == ['west', 'build', '-d', str(tmp_path), '-t', 'run'] @mock.patch('shutil.which', return_value=None) def your_sha256_hashd(patched_which, tmp_path: Path) -> None: device = CustomSimulatorAdapter(DeviceConfig(build_dir=tmp_path, type='custom')) with pytest.raises(TwisterHarnessException, match='west not found'): device.generate_command() def test_if_unit_binary_adapter_get_command_returns_proper_string(tmp_path: Path) -> None: device = UnitSimulatorAdapter(DeviceConfig(build_dir=tmp_path, type='unit')) device.generate_command() assert isinstance(device.command, list) assert device.command == [str(tmp_path / 'testbinary')] ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/device/binary_adapter_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,852
```python # from __future__ import annotations zen_of_python: list[str] = """ The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! """.split('\n') ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/resources/zen_of_python.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
204
```python # import logging import os import sys import threading import time from argparse import ArgumentParser from zen_of_python import zen_of_python class FifoFile: def __init__(self, filename, mode): self.filename = filename self.mode = mode self.thread = None self.file = None self.logger = logging.getLogger(__name__) def _open(self): self.logger.info(f'Creating fifo file: {self.filename}') end_time = time.time() + 2 while not os.path.exists(self.filename): time.sleep(0.1) if time.time() > end_time: self.logger.error(f'Did not able create fifo file: {self.filename}') return self.file = open(self.filename, self.mode, buffering=0) self.logger.info(f'File created: {self.filename}') def open(self): self.thread = threading.Thread(target=self._open(), daemon=True) self.thread.start() def write(self, data): if self.file: self.file.write(data) def read(self): if self.file: return self.file.readline() def close(self): if self.file: self.file.close() self.thread.join(1) self.logger.info(f'Closed file: {self.filename}') def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def main(): logging.basicConfig(level='DEBUG') parser = ArgumentParser() parser.add_argument('file') args = parser.parse_args() read_path = args.file + '.in' write_path = args.file + '.out' logger = logging.getLogger(__name__) logger.info('Start') with FifoFile(write_path, 'wb') as wf, FifoFile(read_path, 'rb'): for line in zen_of_python: wf.write(f'{line}\n'.encode('utf-8')) time.sleep(1) # give a moment for external programs to collect all outputs return 0 if __name__ == '__main__': sys.exit(main()) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/resources/fifo_mock.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
461
```python # """ Simple shell simulator. """ import sys from zen_of_python import zen_of_python PROMPT = 'uart:~$ ' def main() -> int: print('Start shell simulator', flush=True) print(PROMPT, end='', flush=True) for line in sys.stdin: line = line.strip() print(line, flush=True) if line == 'quit': break elif line == 'zen': for zen_line in zen_of_python: print(zen_line, flush=True) print(PROMPT, end='', flush=True) if __name__ == '__main__': main() ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/resources/shell_simulator.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
135
```python #!/usr/bin/python # """ Simply mock for bash script to use with unit tests. """ import sys import time from argparse import ArgumentParser from zen_of_python import zen_of_python def main() -> int: parser = ArgumentParser() parser.add_argument('--sleep', action='store', default=0, type=float) parser.add_argument('--long-sleep', action='store_true') parser.add_argument('--return-code', action='store', default=0, type=int) parser.add_argument('--exception', action='store_true') args = parser.parse_args() if args.exception: # simulate crashing application raise Exception if args.long_sleep: # prints data and wait for certain time for line in zen_of_python: print(line, flush=True) time.sleep(args.sleep) else: # prints lines with delay for line in zen_of_python: print(line, flush=True) time.sleep(args.sleep) print('End of script', flush=True) print('Returns with code', args.return_code, flush=True) time.sleep(1) # give a moment for external programs to collect all outputs return args.return_code if __name__ == '__main__': sys.exit(main()) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/resources/mock_script.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
268
```python # import pytest import textwrap from unittest import mock from twister_harness.helpers.mcumgr import MCUmgr, MCUmgrException @pytest.fixture(name='mcumgr') def fixture_mcumgr() -> MCUmgr: return MCUmgr.create_for_serial('SERIAL_PORT') @mock.patch('twister_harness.helpers.mcumgr.MCUmgr.run_command', return_value='') def test_if_mcumgr_fixture_generate_proper_command( patched_run_command: mock.Mock, mcumgr: MCUmgr ) -> None: mcumgr.reset_device() patched_run_command.assert_called_with('reset') mcumgr.get_image_list() patched_run_command.assert_called_with('image list') mcumgr.image_upload('/path/to/image', timeout=100) patched_run_command.assert_called_with('-t 100 image upload /path/to/image') mcumgr.image_upload('/path/to/image', slot=2, timeout=100) patched_run_command.assert_called_with('-t 100 image upload /path/to/image -e -n 2') mcumgr.image_test(hash='ABCD') patched_run_command.assert_called_with('image test ABCD') mcumgr.image_confirm(hash='ABCD') patched_run_command.assert_called_with('image confirm ABCD') def test_if_mcumgr_fixture_raises_exception_when_no_hash_to_test(mcumgr: MCUmgr) -> None: cmd_output = textwrap.dedent(""" Images: image=0 slot=0 version: 0.0.0 bootable: true flags: active confirmed hash: 1234 Split status: N/A (0) """) mcumgr.run_command = mock.Mock(return_value=cmd_output) with pytest.raises(MCUmgrException): mcumgr.image_test() def test_if_mcumgr_fixture_parse_image_list(mcumgr: MCUmgr) -> None: cmd_output = textwrap.dedent(""" Images: image=0 slot=0 version: 0.0.0 bootable: true flags: active confirmed hash: 0000 image=0 slot=1 version: 1.1.1 bootable: true flags: hash: 1111 Split status: N/A (0) """) mcumgr.run_command = mock.Mock(return_value=cmd_output) image_list = mcumgr.get_image_list() assert image_list[0].image == 0 assert image_list[0].slot == 0 assert image_list[0].version == '0.0.0' assert image_list[0].flags == 'active confirmed' assert image_list[0].hash == '0000' assert image_list[1].image == 0 assert image_list[1].slot == 1 assert image_list[1].version == '1.1.1' assert image_list[1].flags == '' assert image_list[1].hash == '1111' # take second hash to test mcumgr.image_test() mcumgr.run_command.assert_called_with('image test 1111') # take first hash to confirm mcumgr.image_confirm() mcumgr.run_command.assert_called_with('image confirm 1111') ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/fixtures/mcumgr_fixture_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
723
```python # from twister_harness.device.binary_adapter import NativeSimulatorAdapter from twister_harness.helpers.shell import Shell def test_if_shell_helper_properly_send_command(shell_simulator_adapter: NativeSimulatorAdapter) -> None: """Run shell_simulator.py program, send "zen" command via shell helper and verify output.""" shell = Shell(shell_simulator_adapter, timeout=5.0) assert shell.wait_for_prompt() lines = shell.exec_command('zen') assert 'The Zen of Python, by Tim Peters' in lines ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/helpers/shell_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
116
```python # import textwrap from twister_harness.helpers.shell import ShellMCUbootCommandParsed, ShellMCUbootArea def test_if_mcuboot_command_output_is_parsed_two_areas() -> None: cmd_output = textwrap.dedent(""" \x1b[1;32muart:~$ \x1b[mmcuboot swap type: revert confirmed: 0 primary area (1): version: 0.0.2+0 image size: 68240 magic: good swap type: test copy done: set image ok: unset secondary area (3): version: 0.0.0+0 image size: 68240 magic: unset swap type: none copy done: unset image ok: unset \x1b[1;32muart:~$ \x1b[m """) mcuboot_parsed = ShellMCUbootCommandParsed.create_from_cmd_output(cmd_output.splitlines()) assert isinstance(mcuboot_parsed, ShellMCUbootCommandParsed) assert isinstance(mcuboot_parsed.areas[0], ShellMCUbootArea) assert len(mcuboot_parsed.areas) == 2 assert mcuboot_parsed.areas[0].version == '0.0.2+0' assert mcuboot_parsed.areas[0].swap_type == 'test' def test_if_mcuboot_command_output_is_parsed_with_failed_area() -> None: cmd_output = textwrap.dedent(""" \x1b[1;32muart:~$ \x1b[mmcuboot swap type: revert confirmed: 0 primary area (1): version: 1.1.1+1 image size: 68240 magic: good swap type: test copy done: set image ok: unset failed to read secondary area (1) header: -5 \x1b[1;32muart:~$ \x1b[m """) mcuboot_parsed = ShellMCUbootCommandParsed.create_from_cmd_output(cmd_output.splitlines()) assert len(mcuboot_parsed.areas) == 1 assert mcuboot_parsed.areas[0].version == '1.1.1+1' ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/tests/helpers/shell_mcuboot_command_parser_test.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
521
```python # # flake8: noqa from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.helpers.mcumgr import MCUmgr from twister_harness.helpers.shell import Shell __all__ = ['DeviceAdapter', 'MCUmgr', 'Shell'] __version__ = '0.0.1' ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/__init__.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
71
```python # from __future__ import annotations import logging import os import pytest from twister_harness.twister_harness_config import TwisterHarnessConfig logger = logging.getLogger(__name__) pytest_plugins = ( 'twister_harness.fixtures' ) def pytest_addoption(parser: pytest.Parser): twister_harness_group = parser.getgroup('Twister harness') twister_harness_group.addoption( '--twister-harness', action='store_true', default=False, help='Activate Twister harness plugin.' ) parser.addini( 'twister_harness', 'Activate Twister harness plugin', type='bool' ) twister_harness_group.addoption( '--base-timeout', type=float, default=60.0, help='Set base timeout (in seconds) used during monitoring if some ' 'operations are finished in a finite amount of time (e.g. waiting ' 'for flashing).' ) twister_harness_group.addoption( '--build-dir', metavar='PATH', help='Directory with built application.' ) twister_harness_group.addoption( '--device-type', choices=('native', 'qemu', 'hardware', 'unit', 'custom'), help='Choose type of device (hardware, qemu, etc.).' ) twister_harness_group.addoption( '--platform', help='Name of used platform (qemu_x86, nrf52840dk/nrf52840, etc.).' ) twister_harness_group.addoption( '--device-serial', help='Serial device for accessing the board (e.g., /dev/ttyACM0).' ) twister_harness_group.addoption( '--device-serial-baud', type=int, default=115200, help='Serial device baud rate (default 115200).' ) twister_harness_group.addoption( '--runner', help='Use the specified west runner (pyocd, nrfjprog, etc.).' ) twister_harness_group.addoption( '--runner-params', action='append', help='Use the specified west runner params.' ) twister_harness_group.addoption( '--device-id', help='ID of connected hardware device (for example 000682459367).' ) twister_harness_group.addoption( '--device-product', help='Product name of connected hardware device (e.g. "STM32 STLink").' ) twister_harness_group.addoption( '--device-serial-pty', help='Script for controlling pseudoterminal.' ) twister_harness_group.addoption( '--flash-before', type=bool, help='Flash device before attaching to serial port' 'This is useful for devices that share the same port for programming' 'and serial console, or use soft-USB, where flash must come first.' ) twister_harness_group.addoption( '--west-flash-extra-args', help='Extend parameters for west flash. ' 'E.g. --west-flash-extra-args="--board-id=foobar,--erase" ' 'will translate to "west flash -- --board-id=foobar --erase".' ) twister_harness_group.addoption( '--pre-script', metavar='PATH', help='Script executed before flashing and connecting to serial.' ) twister_harness_group.addoption( '--post-flash-script', metavar='PATH', help='Script executed after flashing.' ) twister_harness_group.addoption( '--post-script', metavar='PATH', help='Script executed after closing serial connection.' ) twister_harness_group.addoption( '--dut-scope', choices=('function', 'class', 'module', 'package', 'session'), help='The scope for which `dut` and `shell` fixtures are shared.' ) twister_harness_group.addoption( '--twister-fixture', action='append', dest='fixtures', metavar='FIXTURE', default=[], help='Twister fixture supported by this platform. May be given multiple times.' ) def pytest_configure(config: pytest.Config): if config.getoption('help'): return if not (config.getoption('twister_harness') or config.getini('twister_harness')): return _normalize_paths(config) _validate_options(config) config.twister_harness_config = TwisterHarnessConfig.create(config) # type: ignore def _validate_options(config: pytest.Config) -> None: if not config.option.build_dir: raise Exception('--build-dir has to be provided') if not os.path.isdir(config.option.build_dir): raise Exception(f'Provided --build-dir does not exist: {config.option.build_dir}') if not config.option.device_type: raise Exception('--device-type has to be provided') def _normalize_paths(config: pytest.Config) -> None: """Normalize paths provided by user via CLI""" config.option.build_dir = _normalize_path(config.option.build_dir) config.option.pre_script = _normalize_path(config.option.pre_script) config.option.post_script = _normalize_path(config.option.post_script) config.option.post_flash_script = _normalize_path(config.option.post_flash_script) def _normalize_path(path: str | None) -> str: if path is not None: path = os.path.expanduser(os.path.expandvars(path)) path = os.path.normpath(os.path.abspath(path)) return path ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/plugin.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,197
```python # class TwisterHarnessException(Exception): """General Twister harness exception.""" class TwisterHarnessTimeoutException(TwisterHarnessException): """Twister harness timeout exception""" ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/exceptions.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
39
```python # from __future__ import annotations import logging from dataclasses import dataclass, field from pathlib import Path from twister_harness.helpers.domains_helper import get_default_domain_name import pytest logger = logging.getLogger(__name__) @dataclass class DeviceConfig: type: str build_dir: Path base_timeout: float = 60.0 # [s] platform: str = '' serial: str = '' baud: int = 115200 runner: str = '' runner_params: list[str] = field(default_factory=list, repr=False) id: str = '' product: str = '' serial_pty: str = '' flash_before: bool = False west_flash_extra_args: list[str] = field(default_factory=list, repr=False) name: str = '' pre_script: Path | None = None post_script: Path | None = None post_flash_script: Path | None = None fixtures: list[str] = None app_build_dir: Path | None = None def __post_init__(self): domains = self.build_dir / 'domains.yaml' if domains.exists(): self.app_build_dir = self.build_dir / get_default_domain_name(domains) else: self.app_build_dir = self.build_dir @dataclass class TwisterHarnessConfig: """Store Twister harness configuration to have easy access in test.""" devices: list[DeviceConfig] = field(default_factory=list, repr=False) @classmethod def create(cls, config: pytest.Config) -> TwisterHarnessConfig: """Create new instance from pytest.Config.""" devices = [] west_flash_extra_args: list[str] = [] if config.option.west_flash_extra_args: west_flash_extra_args = [w.strip() for w in config.option.west_flash_extra_args.split(',')] runner_params: list[str] = [] if config.option.runner_params: runner_params = [w.strip() for w in config.option.runner_params] device_from_cli = DeviceConfig( type=config.option.device_type, build_dir=_cast_to_path(config.option.build_dir), base_timeout=config.option.base_timeout, platform=config.option.platform, serial=config.option.device_serial, baud=config.option.device_serial_baud, runner=config.option.runner, runner_params=runner_params, id=config.option.device_id, product=config.option.device_product, serial_pty=config.option.device_serial_pty, flash_before=bool(config.option.flash_before), west_flash_extra_args=west_flash_extra_args, pre_script=_cast_to_path(config.option.pre_script), post_script=_cast_to_path(config.option.post_script), post_flash_script=_cast_to_path(config.option.post_flash_script), fixtures=config.option.fixtures, ) devices.append(device_from_cli) return cls( devices=devices ) def _cast_to_path(path: str | None) -> Path | None: if path is None: return None return Path(path) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/twister_harness_config.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
646
```python # import logging from pathlib import Path from typing import Generator, Type import pytest import time from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.device.factory import DeviceFactory from twister_harness.twister_harness_config import DeviceConfig, TwisterHarnessConfig from twister_harness.helpers.shell import Shell from twister_harness.helpers.mcumgr import MCUmgr from twister_harness.helpers.utils import find_in_config logger = logging.getLogger(__name__) @pytest.fixture(scope='session') def twister_harness_config(request: pytest.FixtureRequest) -> TwisterHarnessConfig: """Return twister_harness_config object.""" twister_harness_config: TwisterHarnessConfig = request.config.twister_harness_config # type: ignore return twister_harness_config @pytest.fixture(scope='session') def device_object(twister_harness_config: TwisterHarnessConfig) -> Generator[DeviceAdapter, None, None]: """Return device object - without run application.""" device_config: DeviceConfig = twister_harness_config.devices[0] device_type = device_config.type device_class: Type[DeviceAdapter] = DeviceFactory.get_device(device_type) device_object = device_class(device_config) try: yield device_object finally: # to make sure we close all running processes execution device_object.close() def determine_scope(fixture_name, config): if dut_scope := config.getoption("--dut-scope", None): return dut_scope return 'function' @pytest.fixture(scope=determine_scope) def unlaunched_dut(request: pytest.FixtureRequest, device_object: DeviceAdapter) -> Generator[DeviceAdapter, None, None]: """Return device object - with logs connected, but not run""" device_object.initialize_log_files(request.node.name) try: yield device_object finally: # to make sure we close all running processes execution device_object.close() @pytest.fixture(scope=determine_scope) def dut(request: pytest.FixtureRequest, device_object: DeviceAdapter) -> Generator[DeviceAdapter, None, None]: """Return launched device - with run application.""" device_object.initialize_log_files(request.node.name) try: device_object.launch() yield device_object finally: # to make sure we close all running processes execution device_object.close() @pytest.fixture(scope=determine_scope) def shell(dut: DeviceAdapter) -> Shell: """Return ready to use shell interface""" shell = Shell(dut, timeout=20.0) if prompt := find_in_config(Path(dut.device_config.app_build_dir) / 'zephyr' / '.config', 'CONFIG_SHELL_PROMPT_UART'): shell.prompt = prompt logger.info('Wait for prompt') if not shell.wait_for_prompt(): pytest.fail('Prompt not found') if dut.device_config.type == 'hardware': # after booting up the device, there might appear additional logs # after first prompt, so we need to wait and clear the buffer time.sleep(0.5) dut.clear_buffer() return shell @pytest.fixture(scope='session') def is_mcumgr_available() -> None: if not MCUmgr.is_available(): pytest.skip('mcumgr not available') @pytest.fixture() def mcumgr(is_mcumgr_available: None, dut: DeviceAdapter) -> Generator[MCUmgr, None, None]: yield MCUmgr.create_for_serial(dut.device_config.serial) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/fixtures.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
742
```python # from __future__ import annotations import logging import time from twister_harness.device.fifo_handler import FifoHandler from twister_harness.device.binary_adapter import BinaryAdapterBase from twister_harness.exceptions import TwisterHarnessException from twister_harness.twister_harness_config import DeviceConfig logger = logging.getLogger(__name__) class QemuAdapter(BinaryAdapterBase): def __init__(self, device_config: DeviceConfig) -> None: super().__init__(device_config) qemu_fifo_file_path = self.device_config.build_dir / 'qemu-fifo' self._fifo_connection: FifoHandler = FifoHandler(qemu_fifo_file_path, self.base_timeout) def generate_command(self) -> None: """Set command to run.""" self.command = [self.west, 'build', '-d', str(self.device_config.app_build_dir), '-t', 'run'] if 'stdin' in self.process_kwargs: self.process_kwargs.pop('stdin') def _flash_and_run(self) -> None: super()._flash_and_run() self._create_fifo_connection() def _create_fifo_connection(self) -> None: self._fifo_connection.initiate_connection() timeout_time: float = time.time() + self.base_timeout while time.time() < timeout_time and self._is_binary_running(): if self._fifo_connection.is_open: return time.sleep(0.1) msg = 'Cannot establish communication with QEMU device.' logger.error(msg) raise TwisterHarnessException(msg) def _stop_subprocess(self) -> None: super()._stop_subprocess() self._fifo_connection.disconnect() def _read_device_output(self) -> bytes: try: output = self._fifo_connection.readline() except (OSError, ValueError): # emulation was probably finished and thus fifo file was closed too output = b'' return output def _write_to_device(self, data: bytes) -> None: self._fifo_connection.write(data) self._fifo_connection.flush_write() def _flush_device_output(self) -> None: if self.is_device_running(): self._fifo_connection.flush_read() def is_device_connected(self) -> bool: """Return true if device is connected.""" return bool(super().is_device_connected() and self._fifo_connection.is_open) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/qemu_adapter.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
502
```python # ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/__init__.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2
```python # from __future__ import annotations import logging import os import platform import shlex import signal import subprocess import time import psutil _WINDOWS = platform.system() == 'Windows' def log_command(logger: logging.Logger, msg: str, args: list, level: int = logging.DEBUG) -> None: """ Platform-independent helper for logging subprocess invocations. Will log a command string that can be copy/pasted into a POSIX shell on POSIX platforms. This is not available on Windows, so the entire args array is logged instead. :param logger: logging.Logger to use :param msg: message to associate with the command :param args: argument list as passed to subprocess module :param level: log level """ msg = f'{msg}: %s' if _WINDOWS: logger.log(level, msg, str(args)) else: logger.log(level, msg, shlex.join(args)) def terminate_process(proc: subprocess.Popen) -> None: """ Try to terminate provided process and all its subprocesses recursively. """ for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except (ProcessLookupError, psutil.NoSuchProcess): pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/utils.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
305
```python # Tip: You can view just the documentation with 'pydoc3 devicetree.edtlib' """ Library for working with devicetrees at a higher level compared to dtlib. Like dtlib, this library presents a tree of devicetree nodes, but the nodes are augmented with information from bindings and include some interpretation of properties. Some of this interpretation is based on conventions established by the Linux kernel, so the Documentation/devicetree/bindings in the Linux source code is sometimes good reference material. Bindings are YAML files that describe devicetree nodes. Devicetree nodes are usually mapped to bindings via their 'compatible = "..."' property, but a binding can also come from a 'child-binding:' key in the binding for the parent devicetree node. Each devicetree node (dtlib.Node) gets a corresponding edtlib.Node instance, which has all the information related to the node. The top-level entry points for the library are the EDT and Binding classes. See their constructor docstrings for details. There is also a bindings_from_paths() helper function. """ # NOTE: tests/test_edtlib.py is the test suite for this library. # Implementation notes # -------------------- # # A '_' prefix on an identifier in Python is a convention for marking it private. # Please do not access private things. Instead, think of what API you need, and # add it. # # This module is not meant to have any global state. It should be possible to # create several EDT objects with independent binding paths and flags. If you # need to add a configuration parameter or the like, store it in the EDT # instance, and initialize it e.g. with a constructor argument. # # This library is layered on top of dtlib, and is not meant to expose it to # clients. This keeps the header generation script simple. # # General biased advice: # # - Consider using @property for APIs that don't need parameters. It makes # functions look like attributes, which is less awkward in clients, and makes # it easy to switch back and forth between variables and functions. # # - Think about the data type of the thing you're exposing. Exposing something # as e.g. a list or a dictionary is often nicer and more flexible than adding # a function. # # - Avoid get_*() prefixes on functions. Name them after the thing they return # instead. This often makes the code read more naturally in callers. # # Also, consider using @property instead of get_*(). # # - Don't expose dtlib stuff directly. # # - Add documentation for any new APIs you add. # # The convention here is that docstrings (quoted strings) are used for public # APIs, and "doc comments" for internal functions. # # @properties are documented in the class docstring, as if they were # variables. See the existing @properties for a template. from collections import defaultdict from copy import deepcopy from dataclasses import dataclass from typing import Any, Callable, Dict, Iterable, List, NoReturn, \ Optional, Set, TYPE_CHECKING, Tuple, Union import logging import os import re import yaml try: # Use the C LibYAML parser if available, rather than the Python parser. # This makes e.g. gen_defines.py more than twice as fast. from yaml import CLoader as Loader except ImportError: from yaml import Loader # type: ignore from devicetree.dtlib import DT, DTError, to_num, to_nums, Type from devicetree.dtlib import Node as dtlib_Node from devicetree.dtlib import Property as dtlib_Property from devicetree.grutils import Graph from devicetree._private import _slice_helper # # Public classes # class Binding: """ Represents a parsed binding. These attributes are available on Binding objects: path: The absolute path to the file defining the binding. description: The free-form description of the binding, or None. compatible: The compatible string the binding matches. This may be None. For example, it's None when the Binding is inferred from node properties. It can also be None for Binding objects created using 'child-binding:' with no compatible. prop2specs: A dict mapping property names to PropertySpec objects describing those properties' values. specifier2cells: A dict that maps specifier space names (like "gpio", "clock", "pwm", etc.) to lists of cell names. For example, if the binding YAML contains 'pin' and 'flags' cell names for the 'gpio' specifier space, like this: gpio-cells: - pin - flags Then the Binding object will have a 'specifier2cells' attribute mapping "gpio" to ["pin", "flags"]. A missing key should be interpreted as zero cells. raw: The binding as an object parsed from YAML. bus: If nodes with this binding's 'compatible' describe a bus, a string describing the bus type (like "i2c") or a list describing supported protocols (like ["i3c", "i2c"]). None otherwise. Note that this is the raw value from the binding where it can be a string or a list. Use "buses" instead unless you need the raw value, where "buses" is always a list. buses: Deprived property from 'bus' where 'buses' is a list of bus(es), for example, ["i2c"] or ["i3c", "i2c"]. Or an empty list if there is no 'bus:' in this binding. on_bus: If nodes with this binding's 'compatible' appear on a bus, a string describing the bus type (like "i2c"). None otherwise. child_binding: If this binding describes the properties of child nodes, then this is a Binding object for those children; it is None otherwise. A Binding object's 'child_binding.child_binding' is not None if there are multiple levels of 'child-binding' descriptions in the binding. """ def __init__(self, path: Optional[str], fname2path: Dict[str, str], raw: Any = None, require_compatible: bool = True, require_description: bool = True, inc_allowlist: Optional[List[str]] = None, inc_blocklist: Optional[List[str]] = None): """ Binding constructor. path: Path to binding YAML file. May be None. fname2path: Map from include files to their absolute paths. Must not be None, but may be empty. raw: Optional raw content in the binding. This does not have to have any "include:" lines resolved. May be left out, in which case 'path' is opened and read. This can be used to resolve child bindings, for example. require_compatible: If True, it is an error if the binding does not contain a "compatible:" line. If False, a missing "compatible:" is not an error. Either way, "compatible:" must be a string if it is present in the binding. require_description: If True, it is an error if the binding does not contain a "description:" line. If False, a missing "description:" is not an error. Either way, "description:" must be a string if it is present in the binding. inc_allowlist: The property-allowlist filter set by including bindings. inc_blocklist: The property-blocklist filter set by including bindings. """ self.path: Optional[str] = path self._fname2path: Dict[str, str] = fname2path self._inc_allowlist: Optional[List[str]] = inc_allowlist self._inc_blocklist: Optional[List[str]] = inc_blocklist if raw is None: if path is None: _err("you must provide either a 'path' or a 'raw' argument") with open(path, encoding="utf-8") as f: raw = yaml.load(f, Loader=_BindingLoader) # Get the properties this binding modifies # before we merge the included ones. last_modified_props = list(raw.get("properties", {}).keys()) # Map property names to their specifications: # - first, _merge_includes() will recursively populate prop2specs with # the properties specified by the included bindings # - eventually, we'll update prop2specs with the properties # this binding itself defines or modifies self.prop2specs: Dict[str, 'PropertySpec'] = {} # Merge any included files into self.raw. This also pulls in # inherited child binding definitions, so it has to be done # before initializing those. self.raw: dict = self._merge_includes(raw, self.path) # Recursively initialize any child bindings. These don't # require a 'compatible' or 'description' to be well defined, # but they must be dicts. if "child-binding" in raw: if not isinstance(raw["child-binding"], dict): _err(f"malformed 'child-binding:' in {self.path}, " "expected a binding (dictionary with keys/values)") self.child_binding: Optional['Binding'] = Binding( path, fname2path, raw=raw["child-binding"], require_compatible=False, require_description=False) else: self.child_binding = None # Make sure this is a well defined object. self._check(require_compatible, require_description) # Update specs with the properties this binding defines or modifies. for prop_name in last_modified_props: self.prop2specs[prop_name] = PropertySpec(prop_name, self) # Initialize look up tables. self.specifier2cells: Dict[str, List[str]] = {} for key, val in self.raw.items(): if key.endswith("-cells"): self.specifier2cells[key[:-len("-cells")]] = val def __repr__(self) -> str: if self.compatible: compat = f" for compatible '{self.compatible}'" else: compat = "" basename = os.path.basename(self.path or "") return f"<Binding {basename}" + compat + ">" @property def description(self) -> Optional[str]: "See the class docstring" return self.raw.get('description') @property def compatible(self) -> Optional[str]: "See the class docstring" return self.raw.get('compatible') @property def bus(self) -> Union[None, str, List[str]]: "See the class docstring" return self.raw.get('bus') @property def buses(self) -> List[str]: "See the class docstring" if self.raw.get('bus') is not None: return self._buses else: return [] @property def on_bus(self) -> Optional[str]: "See the class docstring" return self.raw.get('on-bus') def _merge_includes(self, raw: dict, binding_path: Optional[str]) -> dict: # Constructor helper. Merges included files in # 'raw["include"]' into 'raw' using 'self._include_paths' as a # source of include files, removing the "include" key while # doing so. # # This treats 'binding_path' as the binding file being built up # and uses it for error messages. if "include" not in raw: return raw include = raw.pop("include") # First, merge the included files together. If more than one included # file has a 'required:' for a particular property, OR the values # together, so that 'required: true' wins. merged: Dict[str, Any] = {} if isinstance(include, str): # Simple scalar string case # Load YAML file and register property specs into prop2specs. inc_raw = self._load_raw(include, self._inc_allowlist, self._inc_blocklist) _merge_props(merged, inc_raw, None, binding_path, False) elif isinstance(include, list): # List of strings and maps. These types may be intermixed. for elem in include: if isinstance(elem, str): # Load YAML file and register property specs into prop2specs. inc_raw = self._load_raw(elem, self._inc_allowlist, self._inc_blocklist) _merge_props(merged, inc_raw, None, binding_path, False) elif isinstance(elem, dict): name = elem.pop('name', None) # Merge this include property-allowlist filter # with filters from including bindings. allowlist = elem.pop('property-allowlist', None) if allowlist is not None: if self._inc_allowlist: allowlist.extend(self._inc_allowlist) else: allowlist = self._inc_allowlist # Merge this include property-blocklist filter # with filters from including bindings. blocklist = elem.pop('property-blocklist', None) if blocklist is not None: if self._inc_blocklist: blocklist.extend(self._inc_blocklist) else: blocklist = self._inc_blocklist child_filter = elem.pop('child-binding', None) if elem: # We've popped out all the valid keys. _err(f"'include:' in {binding_path} should not have " f"these unexpected contents: {elem}") _check_include_dict(name, allowlist, blocklist, child_filter, binding_path) # Load YAML file, and register (filtered) property specs # into prop2specs. contents = self._load_raw(name, allowlist, blocklist, child_filter) _merge_props(merged, contents, None, binding_path, False) else: _err(f"all elements in 'include:' in {binding_path} " "should be either strings or maps with a 'name' key " "and optional 'property-allowlist' or " f"'property-blocklist' keys, but got: {elem}") else: # Invalid item. _err(f"'include:' in {binding_path} " f"should be a string or list, but has type {type(include)}") # Next, merge the merged included files into 'raw'. Error out if # 'raw' has 'required: false' while the merged included files have # 'required: true'. _merge_props(raw, merged, None, binding_path, check_required=True) return raw def _load_raw(self, fname: str, allowlist: Optional[List[str]] = None, blocklist: Optional[List[str]] = None, child_filter: Optional[dict] = None) -> dict: # Returns the contents of the binding given by 'fname' after merging # any bindings it lists in 'include:' into it, according to the given # property filters. # # Will also register the (filtered) included property specs # into prop2specs. path = self._fname2path.get(fname) if not path: _err(f"'{fname}' not found") with open(path, encoding="utf-8") as f: contents = yaml.load(f, Loader=_BindingLoader) if not isinstance(contents, dict): _err(f'{path}: invalid contents, expected a mapping') # Apply constraints to included YAML contents. _filter_properties(contents, allowlist, blocklist, child_filter, self.path) # Register included property specs. self._add_included_prop2specs(fname, contents, allowlist, blocklist) return self._merge_includes(contents, path) def _add_included_prop2specs(self, fname: str, contents: dict, allowlist: Optional[List[str]] = None, blocklist: Optional[List[str]] = None) -> None: # Registers the properties specified by an included binding file # into the properties this binding supports/requires (aka prop2specs). # # Consider "this" binding B includes I1 which itself includes I2. # # We assume to be called in that order: # 1) _add_included_prop2spec(B, I1) # 2) _add_included_prop2spec(B, I2) # # Where we don't want I2 "taking ownership" for properties # modified by I1. # # So we: # - first create a binding that represents the included file # - then add the property specs defined by this binding to prop2specs, # without overriding the specs modified by an including binding # # Note: Unfortunately, we can't cache these base bindings, # as a same YAML file may be included with different filters # (property-allowlist and such), leading to different contents. inc_binding = Binding( self._fname2path[fname], self._fname2path, contents, require_compatible=False, require_description=False, # Recursively pass filters to included bindings. inc_allowlist=allowlist, inc_blocklist=blocklist, ) for prop, spec in inc_binding.prop2specs.items(): if prop not in self.prop2specs: self.prop2specs[prop] = spec def _check(self, require_compatible: bool, require_description: bool): # Does sanity checking on the binding. raw = self.raw if "compatible" in raw: compatible = raw["compatible"] if not isinstance(compatible, str): _err(f"malformed 'compatible: {compatible}' " f"field in {self.path} - " f"should be a string, not {type(compatible).__name__}") elif require_compatible: _err(f"missing 'compatible' in {self.path}") if "description" in raw: description = raw["description"] if not isinstance(description, str) or not description: _err(f"malformed or empty 'description' in {self.path}") elif require_description: _err(f"missing 'description' in {self.path}") # Allowed top-level keys. The 'include' key should have been # removed by _load_raw() already. ok_top = {"description", "compatible", "bus", "on-bus", "properties", "child-binding"} # Descriptive errors for legacy bindings. legacy_errors = { "#cells": "expected *-cells syntax", "child": "use 'bus: <bus>' instead", "child-bus": "use 'bus: <bus>' instead", "parent": "use 'on-bus: <bus>' instead", "parent-bus": "use 'on-bus: <bus>' instead", "sub-node": "use 'child-binding' instead", "title": "use 'description' instead", } for key in raw: if key in legacy_errors: _err(f"legacy '{key}:' in {self.path}, {legacy_errors[key]}") if key not in ok_top and not key.endswith("-cells"): _err(f"unknown key '{key}' in {self.path}, " "expected one of {', '.join(ok_top)}, or *-cells") if "bus" in raw: bus = raw["bus"] if not isinstance(bus, str) and \ (not isinstance(bus, list) and \ not all(isinstance(elem, str) for elem in bus)): _err(f"malformed 'bus:' value in {self.path}, " "expected string or list of strings") if isinstance(bus, list): self._buses = bus else: # Convert bus into a list self._buses = [bus] if "on-bus" in raw and \ not isinstance(raw["on-bus"], str): _err(f"malformed 'on-bus:' value in {self.path}, " "expected string") self._check_properties() for key, val in raw.items(): if key.endswith("-cells"): if not isinstance(val, list) or \ not all(isinstance(elem, str) for elem in val): _err(f"malformed '{key}:' in {self.path}, " "expected a list of strings") def _check_properties(self) -> None: # _check() helper for checking the contents of 'properties:'. raw = self.raw if "properties" not in raw: return ok_prop_keys = {"description", "type", "required", "enum", "const", "default", "deprecated", "specifier-space"} for prop_name, options in raw["properties"].items(): for key in options: if key not in ok_prop_keys: _err(f"unknown setting '{key}' in " f"'properties: {prop_name}: ...' in {self.path}, " f"expected one of {', '.join(ok_prop_keys)}") _check_prop_by_type(prop_name, options, self.path) for true_false_opt in ["required", "deprecated"]: if true_false_opt in options: option = options[true_false_opt] if not isinstance(option, bool): _err(f"malformed '{true_false_opt}:' setting '{option}' " f"for '{prop_name}' in 'properties' in {self.path}, " "expected true/false") if options.get("deprecated") and options.get("required"): _err(f"'{prop_name}' in 'properties' in {self.path} should not " "have both 'deprecated' and 'required' set") if "description" in options and \ not isinstance(options["description"], str): _err("missing, malformed, or empty 'description' for " f"'{prop_name}' in 'properties' in {self.path}") if "enum" in options and not isinstance(options["enum"], list): _err(f"enum in {self.path} for property '{prop_name}' " "is not a list") class PropertySpec: """ Represents a "property specification", i.e. the description of a property provided by a binding file, like its type and description. These attributes are available on PropertySpec objects: binding: The Binding object which defined this property. name: The property's name. path: The file where this property was defined. In case a binding includes other bindings, this is the file where the property was last modified. type: The type of the property as a string, as given in the binding. description: The free-form description of the property as a string, or None. enum: A list of values the property may take as given in the binding, or None. enum_tokenizable: True if enum is not None and all the values in it are tokenizable; False otherwise. A property must have string type and an "enum:" in its binding to be tokenizable. Additionally, the "enum:" values must be unique after converting all non-alphanumeric characters to underscores (so "foo bar" and "foo_bar" in the same "enum:" would not be tokenizable). enum_upper_tokenizable: Like 'enum_tokenizable', with the additional restriction that the "enum:" values must be unique after uppercasing and converting non-alphanumeric characters to underscores. const: The property's constant value as given in the binding, or None. default: The property's default value as given in the binding, or None. deprecated: True if the property is deprecated; False otherwise. required: True if the property is marked required; False otherwise. specifier_space: The specifier space for the property as given in the binding, or None. """ def __init__(self, name: str, binding: Binding): self.binding: Binding = binding self.name: str = name self._raw: Dict[str, Any] = self.binding.raw["properties"][name] def __repr__(self) -> str: return f"<PropertySpec {self.name} type '{self.type}'>" @property def path(self) -> Optional[str]: "See the class docstring" return self.binding.path @property def type(self) -> str: "See the class docstring" return self._raw["type"] @property def description(self) -> Optional[str]: "See the class docstring" return self._raw.get("description") @property def enum(self) -> Optional[list]: "See the class docstring" return self._raw.get("enum") @property def enum_tokenizable(self) -> bool: "See the class docstring" if not hasattr(self, '_enum_tokenizable'): if self.type != 'string' or self.enum is None: self._enum_tokenizable = False else: # Saving _as_tokens here lets us reuse it in # enum_upper_tokenizable. self._as_tokens = [re.sub(_NOT_ALPHANUM_OR_UNDERSCORE, '_', value) for value in self.enum] self._enum_tokenizable = (len(self._as_tokens) == len(set(self._as_tokens))) return self._enum_tokenizable @property def enum_upper_tokenizable(self) -> bool: "See the class docstring" if not hasattr(self, '_enum_upper_tokenizable'): if not self.enum_tokenizable: self._enum_upper_tokenizable = False else: self._enum_upper_tokenizable = \ (len(self._as_tokens) == len(set(x.upper() for x in self._as_tokens))) return self._enum_upper_tokenizable @property def const(self) -> Union[None, int, List[int], str, List[str]]: "See the class docstring" return self._raw.get("const") @property def default(self) -> Union[None, int, List[int], str, List[str]]: "See the class docstring" return self._raw.get("default") @property def required(self) -> bool: "See the class docstring" return self._raw.get("required", False) @property def deprecated(self) -> bool: "See the class docstring" return self._raw.get("deprecated", False) @property def specifier_space(self) -> Optional[str]: "See the class docstring" return self._raw.get("specifier-space") PropertyValType = Union[int, str, List[int], List[str], 'Node', List['Node'], List[Optional['ControllerAndData']], bytes, None] @dataclass class Property: """ Represents a property on a Node, as set in its DT node and with additional info from the 'properties:' section of the binding. Only properties mentioned in 'properties:' get created. Properties of type 'compound' currently do not get Property instances, as it's not clear what to generate for them. These attributes are available on Property objects. Several are just convenience accessors for attributes on the PropertySpec object accessible via the 'spec' attribute. These attributes are available on Property objects: spec: The PropertySpec object which specifies this property. val: The value of the property, with the format determined by spec.type, which comes from the 'type:' string in the binding. - For 'type: int/array/string/string-array', 'val' is what you'd expect (a Python integer or string, or a list of them) - For 'type: phandle' and 'type: path', 'val' is the pointed-to Node instance - For 'type: phandles', 'val' is a list of the pointed-to Node instances - For 'type: phandle-array', 'val' is a list of ControllerAndData instances. See the documentation for that class. node: The Node instance the property is on name: Convenience for spec.name. description: Convenience for spec.description with leading and trailing whitespace (including newlines) removed. May be None. type: Convenience for spec.type. val_as_token: The value of the property as a token, i.e. with non-alphanumeric characters replaced with underscores. This is only safe to access if 'spec.enum_tokenizable' returns True. enum_index: The index of 'val' in 'spec.enum' (which comes from the 'enum:' list in the binding), or None if spec.enum is None. """ spec: PropertySpec val: PropertyValType node: 'Node' @property def name(self) -> str: "See the class docstring" return self.spec.name @property def description(self) -> Optional[str]: "See the class docstring" return self.spec.description.strip() if self.spec.description else None @property def type(self) -> str: "See the class docstring" return self.spec.type @property def val_as_token(self) -> str: "See the class docstring" assert isinstance(self.val, str) return str_as_token(self.val) @property def enum_index(self) -> Optional[int]: "See the class docstring" enum = self.spec.enum return enum.index(self.val) if enum else None @dataclass class Register: """ Represents a register on a node. These attributes are available on Register objects: node: The Node instance this register is from name: The name of the register as given in the 'reg-names' property, or None if there is no 'reg-names' property addr: The starting address of the register, in the parent address space, or None if #address-cells is zero. Any 'ranges' properties are taken into account. size: The length of the register in bytes """ node: 'Node' name: Optional[str] addr: Optional[int] size: Optional[int] @dataclass class Range: """ Represents a translation range on a node as described by the 'ranges' property. These attributes are available on Range objects: node: The Node instance this range is from child_bus_cells: The number of cells used to describe a child bus address. child_bus_addr: A physical address within the child bus address space, or None if the child's #address-cells equals 0. parent_bus_cells: The number of cells used to describe a parent bus address. parent_bus_addr: A physical address within the parent bus address space, or None if the parent's #address-cells equals 0. length_cells: The number of cells used to describe the size of range in the child's address space. length: The size of the range in the child address space, or None if the child's #size-cells equals 0. """ node: 'Node' child_bus_cells: int child_bus_addr: Optional[int] parent_bus_cells: int parent_bus_addr: Optional[int] length_cells: int length: Optional[int] @dataclass class ControllerAndData: """ Represents an entry in an 'interrupts' or 'type: phandle-array' property value, e.g. <&ctrl-1 4 0> in cs-gpios = <&ctrl-1 4 0 &ctrl-2 3 4>; These attributes are available on ControllerAndData objects: node: The Node instance the property appears on controller: The Node instance for the controller (e.g. the controller the interrupt gets sent to for interrupts) data: A dictionary that maps names from the *-cells key in the binding for the controller to data values, e.g. {"pin": 4, "flags": 0} for the example above. 'interrupts = <1 2>' might give {"irq": 1, "level": 2}. name: The name of the entry as given in 'interrupt-names'/'gpio-names'/'pwm-names'/etc., or None if there is no *-names property basename: Basename for the controller when supporting named cells """ node: 'Node' controller: 'Node' data: dict name: Optional[str] basename: Optional[str] @dataclass class PinCtrl: """ Represents a pin control configuration for a set of pins on a device, e.g. pinctrl-0 or pinctrl-1. These attributes are available on PinCtrl objects: node: The Node instance the pinctrl-* property is on name: The name of the configuration, as given in pinctrl-names, or None if there is no pinctrl-names property name_as_token: Like 'name', but with non-alphanumeric characters converted to underscores. conf_nodes: A list of Node instances for the pin configuration nodes, e.g. the nodes pointed at by &state_1 and &state_2 in pinctrl-0 = <&state_1 &state_2>; """ node: 'Node' name: Optional[str] conf_nodes: List['Node'] @property def name_as_token(self): "See the class docstring" return str_as_token(self.name) if self.name is not None else None class Node: """ Represents a devicetree node, augmented with information from bindings, and with some interpretation of devicetree properties. There's a one-to-one correspondence between devicetree nodes and Nodes. These attributes are available on Node objects: edt: The EDT instance this node is from name: The name of the node unit_addr: An integer with the ...@<unit-address> portion of the node name, translated through any 'ranges' properties on parent nodes, or None if the node name has no unit-address portion. PCI devices use a different node name format ...@<dev>,<func> or ...@<dev> (e.g. "pcie@1,0"), in this case None is returned. description: The description string from the binding for the node, or None if the node has no binding. Leading and trailing whitespace (including newlines) is removed. path: The devicetree path of the node label: The text from the 'label' property on the node, or None if the node has no 'label' labels: A list of all of the devicetree labels for the node, in the same order as the labels appear, but with duplicates removed. This corresponds to the actual devicetree source labels, unlike the "label" attribute, which is the value of a devicetree property named "label". parent: The Node instance for the devicetree parent of the Node, or None if the node is the root node children: A dictionary with the Node instances for the devicetree children of the node, indexed by name dep_ordinal: A non-negative integer value such that the value for a Node is less than the value for all Nodes that depend on it. The ordinal is defined for all Nodes, and is unique among nodes in its EDT 'nodes' list. required_by: A list with the nodes that directly depend on the node depends_on: A list with the nodes that the node directly depends on status: The node's status property value, as a string, or "okay" if the node has no status property set. If the node's status property is "ok", it is converted to "okay" for consistency. read_only: True if the node has a 'read-only' property, and False otherwise matching_compat: The 'compatible' string for the binding that matched the node, or None if the node has no binding binding_path: The path to the binding file for the node, or None if the node has no binding compats: A list of 'compatible' strings for the node, in the same order that they're listed in the .dts file ranges: A list of Range objects extracted from the node's ranges property. The list is empty if the node does not have a range property. regs: A list of Register objects for the node's registers props: A dict that maps property names to Property objects. Property objects are created for all devicetree properties on the node that are mentioned in 'properties:' in the binding. aliases: A list of aliases for the node. This is fetched from the /aliases node. interrupts: A list of ControllerAndData objects for the interrupts generated by the node. The list is empty if the node does not generate interrupts. pinctrls: A list of PinCtrl objects for the pinctrl-<index> properties on the node, sorted by index. The list is empty if the node does not have any pinctrl-<index> properties. buses: If the node is a bus node (has a 'bus:' key in its binding), then this attribute holds the list of supported bus types, e.g. ["i2c"], ["spi"] or ["i3c", "i2c"] if multiple protocols are supported via the same bus. If the node is not a bus node, then this attribute is an empty list. on_buses: The bus the node appears on, e.g. ["i2c"], ["spi"] or ["i3c", "i2c"] if multiple protocols are supported via the same bus. The bus is determined by searching upwards for a parent node whose binding has a 'bus:' key, returning the value of the first 'bus:' key found. If none of the node's parents has a 'bus:' key, this attribute is an empty list. bus_node: Like on_bus, but contains the Node for the bus controller, or None if the node is not on a bus. flash_controller: The flash controller for the node. Only meaningful for nodes representing flash partitions. spi_cs_gpio: The device's SPI GPIO chip select as a ControllerAndData instance, if it exists, and None otherwise. See Documentation/devicetree/bindings/spi/spi-controller.yaml in the Linux kernel. gpio_hogs: A list of ControllerAndData objects for the GPIOs hogged by the node. The list is empty if the node does not hog any GPIOs. Only relevant for GPIO hog nodes. is_pci_device: True if the node is a PCI device. """ def __init__(self, dt_node: dtlib_Node, edt: 'EDT', compats: List[str]): ''' For internal use only; not meant to be used outside edtlib itself. ''' # Public, some of which are initialized properly later: self.edt: 'EDT' = edt self.dep_ordinal: int = -1 self.matching_compat: Optional[str] = None self.binding_path: Optional[str] = None self.compats: List[str] = compats self.ranges: List[Range] = [] self.regs: List[Register] = [] self.props: Dict[str, Property] = {} self.interrupts: List[ControllerAndData] = [] self.pinctrls: List[PinCtrl] = [] self.bus_node: Optional['Node'] = None # Private, don't touch outside the class: self._node: dtlib_Node = dt_node self._binding: Optional[Binding] = None @property def name(self) -> str: "See the class docstring" return self._node.name @property def unit_addr(self) -> Optional[int]: "See the class docstring" # TODO: Return a plain string here later, like dtlib.Node.unit_addr? # PCI devices use a different node name format (e.g. "pcie@1,0") if "@" not in self.name or self.is_pci_device: return None try: addr = int(self.name.split("@", 1)[1], 16) except ValueError: _err(f"{self!r} has non-hex unit address") return _translate(addr, self._node) @property def description(self) -> Optional[str]: "See the class docstring." if self._binding: return self._binding.description return None @property def path(self) -> str: "See the class docstring" return self._node.path @property def label(self) -> Optional[str]: "See the class docstring" if "label" in self._node.props: return self._node.props["label"].to_string() return None @property def labels(self) -> List[str]: "See the class docstring" return self._node.labels @property def parent(self) -> Optional['Node']: "See the class docstring" return self.edt._node2enode.get(self._node.parent) # type: ignore @property def children(self) -> Dict[str, 'Node']: "See the class docstring" # Could be initialized statically too to preserve identity, but not # sure if needed. Parent nodes being initialized before their children # would need to be kept in mind. return {name: self.edt._node2enode[node] for name, node in self._node.nodes.items()} def child_index(self, node) -> int: """Get the index of *node* in self.children. Raises KeyError if the argument is not a child of this node. """ if not hasattr(self, '_child2index'): # Defer initialization of this lookup table until this # method is callable to handle parents needing to be # initialized before their chidlren. By the time we # return from __init__, 'self.children' is callable. self._child2index: Dict[str, int] = {} for index, child_path in enumerate(child.path for child in self.children.values()): self._child2index[child_path] = index return self._child2index[node.path] @property def required_by(self) -> List['Node']: "See the class docstring" return self.edt._graph.required_by(self) @property def depends_on(self) -> List['Node']: "See the class docstring" return self.edt._graph.depends_on(self) @property def status(self) -> str: "See the class docstring" status = self._node.props.get("status") if status is None: as_string = "okay" else: as_string = status.to_string() if as_string == "ok": as_string = "okay" return as_string @property def read_only(self) -> bool: "See the class docstring" return "read-only" in self._node.props @property def aliases(self) -> List[str]: "See the class docstring" return [alias for alias, node in self._node.dt.alias2node.items() if node is self._node] @property def buses(self) -> List[str]: "See the class docstring" if self._binding: return self._binding.buses return [] @property def on_buses(self) -> List[str]: "See the class docstring" bus_node = self.bus_node return bus_node.buses if bus_node else [] @property def flash_controller(self) -> 'Node': "See the class docstring" # The node path might be something like # /flash-controller@4001E000/flash@0/partitions/partition@fc000. We go # up two levels to get the flash and check its compat. The flash # controller might be the flash itself (for cases like NOR flashes). # For the case of 'soc-nv-flash', we assume the controller is the # parent of the flash node. if not self.parent or not self.parent.parent: _err(f"flash partition {self!r} lacks parent or grandparent node") controller = self.parent.parent if controller.matching_compat == "soc-nv-flash": if controller.parent is None: _err(f"flash controller '{controller.path}' cannot be the root node") return controller.parent return controller @property def spi_cs_gpio(self) -> Optional[ControllerAndData]: "See the class docstring" if not ("spi" in self.on_buses and self.bus_node and "cs-gpios" in self.bus_node.props): return None if not self.regs: _err(f"{self!r} needs a 'reg' property, to look up the " "chip select index for SPI") parent_cs_lst = self.bus_node.props["cs-gpios"].val if TYPE_CHECKING: assert isinstance(parent_cs_lst, list) # cs-gpios is indexed by the unit address cs_index = self.regs[0].addr if TYPE_CHECKING: assert isinstance(cs_index, int) if cs_index >= len(parent_cs_lst): _err(f"index from 'regs' in {self!r} ({cs_index}) " "is >= number of cs-gpios in " f"{self.bus_node!r} ({len(parent_cs_lst)})") ret = parent_cs_lst[cs_index] if TYPE_CHECKING: assert isinstance(ret, ControllerAndData) return ret @property def gpio_hogs(self) -> List[ControllerAndData]: "See the class docstring" if "gpio-hog" not in self.props: return [] if not self.parent or not "gpio-controller" in self.parent.props: _err(f"GPIO hog {self!r} lacks parent GPIO controller node") if not "#gpio-cells" in self.parent._node.props: _err(f"GPIO hog {self!r} parent node lacks #gpio-cells") n_cells = self.parent._node.props["#gpio-cells"].to_num() res = [] for item in _slice(self._node, "gpios", 4*n_cells, f"4*(<#gpio-cells> (= {n_cells})"): controller = self.parent res.append(ControllerAndData( node=self, controller=controller, data=self._named_cells(controller, item, "gpio"), name=None, basename="gpio")) return res @property def is_pci_device(self) -> bool: "See the class docstring" return 'pcie' in self.on_buses def __repr__(self) -> str: if self.binding_path: binding = "binding " + self.binding_path else: binding = "no binding" return f"<Node {self.path} in '{self.edt.dts_path}', {binding}>" def _init_binding(self) -> None: # Initializes Node.matching_compat, Node._binding, and # Node.binding_path. # # Node._binding holds the data from the node's binding file, in the # format returned by PyYAML (plain Python lists, dicts, etc.), or None # if the node has no binding. # This relies on the parent of the node having already been # initialized, which is guaranteed by going through the nodes in # node_iter() order. if self.path in self.edt._infer_binding_for_paths: self._binding_from_properties() return if self.compats: on_buses = self.on_buses for compat in self.compats: # When matching, respect the order of the 'compatible' entries, # and for each one first try to match against an explicitly # specified bus (if any) and then against any bus. This is so # that matching against bindings which do not specify a bus # works the same way in Zephyr as it does elsewhere. binding = None for bus in on_buses: if (compat, bus) in self.edt._compat2binding: binding = self.edt._compat2binding[compat, bus] break if not binding: if (compat, None) in self.edt._compat2binding: binding = self.edt._compat2binding[compat, None] else: continue self.binding_path = binding.path self.matching_compat = compat self._binding = binding return else: # No 'compatible' property. See if the parent binding has # a compatible. This can come from one or more levels of # nesting with 'child-binding:'. binding_from_parent = self._binding_from_parent() if binding_from_parent: self._binding = binding_from_parent self.binding_path = self._binding.path self.matching_compat = self._binding.compatible return # No binding found self._binding = self.binding_path = self.matching_compat = None def _binding_from_properties(self) -> None: # Sets up a Binding object synthesized from the properties in the node. if self.compats: _err(f"compatible in node with inferred binding: {self.path}") # Synthesize a 'raw' binding as if it had been parsed from YAML. raw: Dict[str, Any] = { 'description': 'Inferred binding from properties, via edtlib.', 'properties': {}, } for name, prop in self._node.props.items(): pp: Dict[str, str] = {} if prop.type == Type.EMPTY: pp["type"] = "boolean" elif prop.type == Type.BYTES: pp["type"] = "uint8-array" elif prop.type == Type.NUM: pp["type"] = "int" elif prop.type == Type.NUMS: pp["type"] = "array" elif prop.type == Type.STRING: pp["type"] = "string" elif prop.type == Type.STRINGS: pp["type"] = "string-array" elif prop.type == Type.PHANDLE: pp["type"] = "phandle" elif prop.type == Type.PHANDLES: pp["type"] = "phandles" elif prop.type == Type.PHANDLES_AND_NUMS: pp["type"] = "phandle-array" elif prop.type == Type.PATH: pp["type"] = "path" else: _err(f"cannot infer binding from property: {prop} " f"with type {prop.type!r}") raw['properties'][name] = pp # Set up Node state. self.binding_path = None self.matching_compat = None self.compats = [] self._binding = Binding(None, {}, raw=raw, require_compatible=False) def _binding_from_parent(self) -> Optional[Binding]: # Returns the binding from 'child-binding:' in the parent node's # binding. if not self.parent: return None pbinding = self.parent._binding if not pbinding: return None if pbinding.child_binding: return pbinding.child_binding return None def _bus_node(self, support_fixed_partitions_on_any_bus: bool = True ) -> Optional['Node']: # Returns the value for self.bus_node. Relies on parent nodes being # initialized before their children. if not self.parent: # This is the root node return None # Treat 'fixed-partitions' as if they are not on any bus. The reason is # that flash nodes might be on a SPI or controller or SoC bus. Having # bus be None means we'll always match the binding for fixed-partitions # also this means want processing the fixed-partitions node we wouldn't # try to do anything bus specific with it. if support_fixed_partitions_on_any_bus and "fixed-partitions" in self.compats: return None if self.parent.buses: # The parent node is a bus node return self.parent # Same bus node as parent (possibly None) return self.parent.bus_node def _init_props(self, default_prop_types: bool = False, err_on_deprecated: bool = False) -> None: # Creates self.props. See the class docstring. Also checks that all # properties on the node are declared in its binding. self.props = {} node = self._node if self._binding: prop2specs = self._binding.prop2specs else: prop2specs = None # Initialize self.props if prop2specs: for prop_spec in prop2specs.values(): self._init_prop(prop_spec, err_on_deprecated) self._check_undeclared_props() elif default_prop_types: for name in node.props: if name not in _DEFAULT_PROP_SPECS: continue prop_spec = _DEFAULT_PROP_SPECS[name] val = self._prop_val(name, prop_spec.type, False, False, None, None, err_on_deprecated) self.props[name] = Property(prop_spec, val, self) def _init_prop(self, prop_spec: PropertySpec, err_on_deprecated: bool) -> None: # _init_props() helper for initializing a single property. # 'prop_spec' is a PropertySpec object from the node's binding. name = prop_spec.name prop_type = prop_spec.type if not prop_type: _err(f"'{name}' in {self.binding_path} lacks 'type'") val = self._prop_val(name, prop_type, prop_spec.deprecated, prop_spec.required, prop_spec.default, prop_spec.specifier_space, err_on_deprecated) if val is None: # 'required: false' property that wasn't there, or a property type # for which we store no data. return enum = prop_spec.enum if enum and val not in enum: _err(f"value of property '{name}' on {self.path} in " f"{self.edt.dts_path} ({val!r}) is not in 'enum' list in " f"{self.binding_path} ({enum!r})") const = prop_spec.const if const is not None and val != const: _err(f"value of property '{name}' on {self.path} in " f"{self.edt.dts_path} ({val!r}) " "is different from the 'const' value specified in " f"{self.binding_path} ({const!r})") # Skip properties that start with '#', like '#size-cells', and mapping # properties like 'gpio-map'/'interrupt-map' if name[0] == "#" or name.endswith("-map"): return self.props[name] = Property(prop_spec, val, self) def _prop_val(self, name: str, prop_type: str, deprecated: bool, required: bool, default: PropertyValType, specifier_space: Optional[str], err_on_deprecated: bool) -> PropertyValType: # _init_prop() helper for getting the property's value # # name: # Property name from binding # # prop_type: # Property type from binding (a string like "int") # # deprecated: # True if the property is deprecated # # required: # True if the property is required to exist # # default: # Default value to use when the property doesn't exist, or None if # the binding doesn't give a default value # # specifier_space: # Property specifier-space from binding (if prop_type is "phandle-array") # # err_on_deprecated: # If True, a deprecated property is an error instead of warning. node = self._node prop = node.props.get(name) if prop and deprecated: msg = (f"'{name}' is marked as deprecated in 'properties:' " f"in {self.binding_path} for node {node.path}.") if err_on_deprecated: _err(msg) else: _LOG.warning(msg) if not prop: if required and self.status == "okay": _err(f"'{name}' is marked as required in 'properties:' in " f"{self.binding_path}, but does not appear in {node!r}") if default is not None: # YAML doesn't have a native format for byte arrays. We need to # convert those from an array like [0x12, 0x34, ...]. The # format has already been checked in # _check_prop_by_type(). if prop_type == "uint8-array": return bytes(default) # type: ignore return default return False if prop_type == "boolean" else None if prop_type == "boolean": if prop.type != Type.EMPTY: _err("'{0}' in {1!r} is defined with 'type: boolean' in {2}, " "but is assigned a value ('{3}') instead of being empty " "('{0};')".format(name, node, self.binding_path, prop)) return True if prop_type == "int": return prop.to_num() if prop_type == "array": return prop.to_nums() if prop_type == "uint8-array": return prop.to_bytes() if prop_type == "string": return prop.to_string() if prop_type == "string-array": return prop.to_strings() if prop_type == "phandle": return self.edt._node2enode[prop.to_node()] if prop_type == "phandles": return [self.edt._node2enode[node] for node in prop.to_nodes()] if prop_type == "phandle-array": # This type is a bit high-level for dtlib as it involves # information from bindings and *-names properties, so there's no # to_phandle_array() in dtlib. Do the type check ourselves. if prop.type not in (Type.PHANDLE, Type.PHANDLES, Type.PHANDLES_AND_NUMS): _err(f"expected property '{name}' in {node.path} in " f"{node.dt.filename} to be assigned " f"with '{name} = < &foo ... &bar 1 ... &baz 2 3 >' " f"(a mix of phandles and numbers), not '{prop}'") return self._standard_phandle_val_list(prop, specifier_space) if prop_type == "path": return self.edt._node2enode[prop.to_path()] # prop_type == "compound". Checking that the 'type:' # value is valid is done in _check_prop_by_type(). # # 'compound' is a dummy type for properties that don't fit any of the # patterns above, so that we can require all entries in 'properties:' # to have a 'type: ...'. No Property object is created for it. return None def _check_undeclared_props(self) -> None: # Checks that all properties are declared in the binding for prop_name in self._node.props: # Allow a few special properties to not be declared in the binding if prop_name.endswith("-controller") or \ prop_name.startswith("#") or \ prop_name in { "compatible", "status", "ranges", "phandle", "interrupt-parent", "interrupts-extended", "device_type"}: continue if TYPE_CHECKING: assert self._binding if prop_name not in self._binding.prop2specs: _err(f"'{prop_name}' appears in {self._node.path} in " f"{self.edt.dts_path}, but is not declared in " f"'properties:' in {self.binding_path}") def _init_ranges(self) -> None: # Initializes self.ranges node = self._node self.ranges = [] if "ranges" not in node.props: return raw_child_address_cells = node.props.get("#address-cells") parent_address_cells = _address_cells(node) if raw_child_address_cells is None: child_address_cells = 2 # Default value per DT spec. else: child_address_cells = raw_child_address_cells.to_num() raw_child_size_cells = node.props.get("#size-cells") if raw_child_size_cells is None: child_size_cells = 1 # Default value per DT spec. else: child_size_cells = raw_child_size_cells.to_num() # Number of cells for one translation 3-tuple in 'ranges' entry_cells = child_address_cells + parent_address_cells + child_size_cells if entry_cells == 0: if len(node.props["ranges"].value) == 0: return else: _err(f"'ranges' should be empty in {self._node.path} since " f"<#address-cells> = {child_address_cells}, " f"<#address-cells for parent> = {parent_address_cells} and " f"<#size-cells> = {child_size_cells}") for raw_range in _slice(node, "ranges", 4*entry_cells, f"4*(<#address-cells> (= {child_address_cells}) + " "<#address-cells for parent> " f"(= {parent_address_cells}) + " f"<#size-cells> (= {child_size_cells}))"): child_bus_cells = child_address_cells if child_address_cells == 0: child_bus_addr = None else: child_bus_addr = to_num(raw_range[:4*child_address_cells]) parent_bus_cells = parent_address_cells if parent_address_cells == 0: parent_bus_addr = None else: parent_bus_addr = to_num( raw_range[(4*child_address_cells): (4*child_address_cells + 4*parent_address_cells)]) length_cells = child_size_cells if child_size_cells == 0: length = None else: length = to_num( raw_range[(4*child_address_cells + 4*parent_address_cells):]) self.ranges.append(Range(self, child_bus_cells, child_bus_addr, parent_bus_cells, parent_bus_addr, length_cells, length)) def _init_regs(self) -> None: # Initializes self.regs node = self._node self.regs = [] if "reg" not in node.props: return address_cells = _address_cells(node) size_cells = _size_cells(node) for raw_reg in _slice(node, "reg", 4*(address_cells + size_cells), f"4*(<#address-cells> (= {address_cells}) + " f"<#size-cells> (= {size_cells}))"): if address_cells == 0: addr = None else: addr = _translate(to_num(raw_reg[:4*address_cells]), node) if size_cells == 0: size = None else: size = to_num(raw_reg[4*address_cells:]) # Size zero is ok for PCI devices if size_cells != 0 and size == 0 and not self.is_pci_device: _err(f"zero-sized 'reg' in {self._node!r} seems meaningless " "(maybe you want a size of one or #size-cells = 0 " "instead)") # We'll fix up the name when we're done. self.regs.append(Register(self, None, addr, size)) _add_names(node, "reg", self.regs) def _init_pinctrls(self) -> None: # Initializes self.pinctrls from any pinctrl-<index> properties node = self._node # pinctrl-<index> properties pinctrl_props = [prop for name, prop in node.props.items() if re.match("pinctrl-[0-9]+", name)] # Sort by index pinctrl_props.sort(key=lambda prop: prop.name) # Check indices for i, prop in enumerate(pinctrl_props): if prop.name != "pinctrl-" + str(i): _err(f"missing 'pinctrl-{i}' property on {node!r} " "- indices should be contiguous and start from zero") self.pinctrls = [] for prop in pinctrl_props: # We'll fix up the names below. self.pinctrls.append(PinCtrl( node=self, name=None, conf_nodes=[self.edt._node2enode[node] for node in prop.to_nodes()])) _add_names(node, "pinctrl", self.pinctrls) def _init_interrupts(self) -> None: # Initializes self.interrupts node = self._node self.interrupts = [] for controller_node, data in _interrupts(node): # We'll fix up the names below. controller = self.edt._node2enode[controller_node] self.interrupts.append(ControllerAndData( node=self, controller=controller, data=self._named_cells(controller, data, "interrupt"), name=None, basename=None)) _add_names(node, "interrupt", self.interrupts) def _standard_phandle_val_list( self, prop: dtlib_Property, specifier_space: Optional[str] ) -> List[Optional[ControllerAndData]]: # Parses a property like # # <prop.name> = <phandle cell phandle cell ...>; # # where each phandle points to a controller node that has a # # #<specifier_space>-cells = <size>; # # property that gives the number of cells in the value after the # controller's phandle in the property. # # E.g. with a property like # # pwms = <&foo 1 2 &bar 3>; # # If 'specifier_space' is "pwm", then we should have this elsewhere # in the tree: # # foo: ... { # #pwm-cells = <2>; # }; # # bar: ... { # #pwm-cells = <1>; # }; # # These values can be given names using the <specifier_space>-names: # list in the binding for the phandle nodes. # # Also parses any # # <specifier_space>-names = "...", "...", ... # # Returns a list of Optional[ControllerAndData] instances. # # An index is None if the underlying phandle-array element is # unspecified. if not specifier_space: if prop.name.endswith("gpios"): # There's some slight special-casing for *-gpios properties in that # e.g. foo-gpios still maps to #gpio-cells rather than # #foo-gpio-cells specifier_space = "gpio" else: # Strip -s. We've already checked that property names end in -s # if there is no specifier space in _check_prop_by_type(). specifier_space = prop.name[:-1] res: List[Optional[ControllerAndData]] = [] for item in _phandle_val_list(prop, specifier_space): if item is None: res.append(None) continue controller_node, data = item mapped_controller, mapped_data = \ _map_phandle_array_entry(prop.node, controller_node, data, specifier_space) controller = self.edt._node2enode[mapped_controller] # We'll fix up the names below. res.append(ControllerAndData( node=self, controller=controller, data=self._named_cells(controller, mapped_data, specifier_space), name=None, basename=specifier_space)) _add_names(self._node, specifier_space, res) return res def _named_cells( self, controller: 'Node', data: bytes, basename: str ) -> Dict[str, int]: # Returns a dictionary that maps <basename>-cells names given in the # binding for 'controller' to cell values. 'data' is the raw data, as a # byte array. if not controller._binding: _err(f"{basename} controller {controller._node!r} " f"for {self._node!r} lacks binding") if basename in controller._binding.specifier2cells: cell_names: List[str] = controller._binding.specifier2cells[basename] else: # Treat no *-cells in the binding the same as an empty *-cells, so # that bindings don't have to have e.g. an empty 'clock-cells:' for # '#clock-cells = <0>'. cell_names = [] data_list = to_nums(data) if len(data_list) != len(cell_names): _err(f"unexpected '{basename}-cells:' length in binding for " f"{controller._node!r} - {len(cell_names)} " f"instead of {len(data_list)}") return dict(zip(cell_names, data_list)) class EDT: """ Represents a devicetree augmented with information from bindings. These attributes are available on EDT objects: nodes: A list of Node objects for the nodes that appear in the devicetree compat2nodes: A collections.defaultdict that maps each 'compatible' string that appears on some Node to a list of Nodes with that compatible. compat2okay: Like compat2nodes, but just for nodes with status 'okay'. compat2vendor: A collections.defaultdict that maps each 'compatible' string that appears on some Node to a vendor name parsed from vendor_prefixes. compat2model: A collections.defaultdict that maps each 'compatible' string that appears on some Node to a model name parsed from that compatible. label2node: A dict that maps a node label to the node with that label. dep_ord2node: A dict that maps an ordinal to the node with that dependency ordinal. chosen_nodes: A dict that maps the properties defined on the devicetree's /chosen node to their values. 'chosen' is indexed by property name (a string), and values are converted to Node objects. Note that properties of the /chosen node which can't be converted to a Node are not included in the value. dts_path: The .dts path passed to __init__() dts_source: The final DTS source code of the loaded devicetree after merging nodes and processing /delete-node/ and /delete-property/, as a string bindings_dirs: The bindings directory paths passed to __init__() scc_order: A list of lists of Nodes. All elements of each list depend on each other, and the Nodes in any list do not depend on any Node in a subsequent list. Each list defines a Strongly Connected Component (SCC) of the graph. For an acyclic graph each list will be a singleton. Cycles will be represented by lists with multiple nodes. Cycles are not expected to be present in devicetree graphs. The standard library's pickle module can be used to marshal and unmarshal EDT objects. """ def __init__(self, dts: Optional[str], bindings_dirs: List[str], warn_reg_unit_address_mismatch: bool = True, default_prop_types: bool = True, support_fixed_partitions_on_any_bus: bool = True, infer_binding_for_paths: Optional[Iterable[str]] = None, vendor_prefixes: Optional[Dict[str, str]] = None, werror: bool = False): """EDT constructor. dts: Path to devicetree .dts file. Passing None for this value is only for internal use; do not do that outside of edtlib. bindings_dirs: List of paths to directories containing bindings, in YAML format. These directories are recursively searched for .yaml files. warn_reg_unit_address_mismatch (default: True): If True, a warning is logged if a node has a 'reg' property where the address of the first entry does not match the unit address of the node default_prop_types (default: True): If True, default property types will be used when a node has no bindings. support_fixed_partitions_on_any_bus (default True): If True, set the Node.bus for 'fixed-partitions' compatible nodes to None. This allows 'fixed-partitions' binding to match regardless of the bus the 'fixed-partition' is under. infer_binding_for_paths (default: None): An iterable of devicetree paths identifying nodes for which bindings should be inferred from the node content. (Child nodes are not processed.) Pass none if no nodes should support inferred bindings. vendor_prefixes (default: None): A dict mapping vendor prefixes in compatible properties to their descriptions. If given, compatibles in the form "manufacturer,device" for which "manufacturer" is neither a key in the dict nor a specially exempt set of grandfathered-in cases will cause warnings. werror (default: False): If True, some edtlib specific warnings become errors. This currently errors out if 'dts' has any deprecated properties set, or an unknown vendor prefix is used. """ # All instance attributes should be initialized here. # This makes it easy to keep track of them, which makes # implementing __deepcopy__() easier. # If you change this, make sure to update __deepcopy__() too, # and update the tests for that method. # Public attributes (the rest are properties) self.nodes: List[Node] = [] self.compat2nodes: Dict[str, List[Node]] = defaultdict(list) self.compat2okay: Dict[str, List[Node]] = defaultdict(list) self.compat2vendor: Dict[str, str] = defaultdict(str) self.compat2model: Dict[str, str] = defaultdict(str) self.label2node: Dict[str, Node] = {} self.dep_ord2node: Dict[int, Node] = {} self.dts_path: str = dts # type: ignore self.bindings_dirs: List[str] = list(bindings_dirs) # Saved kwarg values for internal use self._warn_reg_unit_address_mismatch: bool = warn_reg_unit_address_mismatch self._default_prop_types: bool = default_prop_types self._fixed_partitions_no_bus: bool = support_fixed_partitions_on_any_bus self._infer_binding_for_paths: Set[str] = set(infer_binding_for_paths or []) self._vendor_prefixes: Dict[str, str] = vendor_prefixes or {} self._werror: bool = bool(werror) # Other internal state self._compat2binding: Dict[Tuple[str, Optional[str]], Binding] = {} self._graph: Graph = Graph() self._binding_paths: List[str] = _binding_paths(self.bindings_dirs) self._binding_fname2path: Dict[str, str] = { os.path.basename(path): path for path in self._binding_paths } self._node2enode: Dict[dtlib_Node, Node] = {} if dts is not None: try: self._dt = DT(dts) except DTError as e: raise EDTError(e) from e self._finish_init() def _finish_init(self) -> None: # This helper exists to make the __deepcopy__() implementation # easier to keep in sync with __init__(). _check_dt(self._dt) self._init_compat2binding() self._init_nodes() self._init_graph() self._init_luts() self._check() def get_node(self, path: str) -> Node: """ Returns the Node at the DT path or alias 'path'. Raises EDTError if the path or alias doesn't exist. """ try: return self._node2enode[self._dt.get_node(path)] except DTError as e: _err(e) @property def chosen_nodes(self) -> Dict[str, Node]: ret: Dict[str, Node] = {} try: chosen = self._dt.get_node("/chosen") except DTError: return ret for name, prop in chosen.props.items(): try: node = prop.to_path() except DTError: # DTS value is not phandle or string, or path doesn't exist continue ret[name] = self._node2enode[node] return ret def chosen_node(self, name: str) -> Optional[Node]: """ Returns the Node pointed at by the property named 'name' in /chosen, or None if the property is missing """ return self.chosen_nodes.get(name) @property def dts_source(self) -> str: return f"{self._dt}" def __repr__(self) -> str: return f"<EDT for '{self.dts_path}', binding directories " \ f"'{self.bindings_dirs}'>" def __deepcopy__(self, memo) -> 'EDT': """ Implements support for the standard library copy.deepcopy() function on EDT instances. """ ret = EDT( None, self.bindings_dirs, warn_reg_unit_address_mismatch=self._warn_reg_unit_address_mismatch, default_prop_types=self._default_prop_types, support_fixed_partitions_on_any_bus=self._fixed_partitions_no_bus, infer_binding_for_paths=set(self._infer_binding_for_paths), vendor_prefixes=dict(self._vendor_prefixes), werror=self._werror ) ret.dts_path = self.dts_path ret._dt = deepcopy(self._dt, memo) ret._finish_init() return ret @property def scc_order(self) -> List[List[Node]]: try: return self._graph.scc_order() except Exception as e: raise EDTError(e) def _process_properties_r(self, root_node, props_node): """ Process props_node properties for dependencies, and add those as dependencies of root_node. Then walk through all the props_node children and do the same recursively, maintaining the same root_node. This ensures that on a node with child nodes, the parent node includes the dependencies of all the child nodes as well as its own. """ # A Node depends on any Nodes present in 'phandle', # 'phandles', or 'phandle-array' property values. for prop in props_node.props.values(): if prop.type == 'phandle': self._graph.add_edge(root_node, prop.val) elif prop.type == 'phandles': if TYPE_CHECKING: assert isinstance(prop.val, list) for phandle_node in prop.val: self._graph.add_edge(root_node, phandle_node) elif prop.type == 'phandle-array': if TYPE_CHECKING: assert isinstance(prop.val, list) for cd in prop.val: if cd is None: continue if TYPE_CHECKING: assert isinstance(cd, ControllerAndData) self._graph.add_edge(root_node, cd.controller) # A Node depends on whatever supports the interrupts it # generates. for intr in props_node.interrupts: self._graph.add_edge(root_node, intr.controller) # If the binding defines child bindings, link the child properties to # the root_node as well. if props_node._binding and props_node._binding.child_binding: for child in props_node.children.values(): if "compatible" in child.props: # Not a child node, normal node on a different binding. continue self._process_properties_r(root_node, child) def _process_properties(self, node): """ Add node dependencies based on own as well as child node properties, start from the node itself. """ self._process_properties_r(node, node) def _init_graph(self) -> None: # Constructs a graph of dependencies between Node instances, # which is usable for computing a partial order over the dependencies. # The algorithm supports detecting dependency loops. # # Actually computing the SCC order is lazily deferred to the # first time the scc_order property is read. for node in self.nodes: # Always insert root node if not node.parent: self._graph.add_node(node) # A Node always depends on its parent. for child in node.children.values(): self._graph.add_edge(child, node) self._process_properties(node) def _init_compat2binding(self) -> None: # Creates self._compat2binding, a dictionary that maps # (<compatible>, <bus>) tuples (both strings) to Binding objects. # # The Binding objects are created from YAML files discovered # in self.bindings_dirs as needed. # # For example, self._compat2binding["company,dev", "can"] # contains the Binding for the 'company,dev' device, when it # appears on the CAN bus. # # For bindings that don't specify a bus, <bus> is None, so that e.g. # self._compat2binding["company,notonbus", None] is the Binding. # # Only bindings for 'compatible' strings that appear in the devicetree # are loaded. dt_compats = _dt_compats(self._dt) # Searches for any 'compatible' string mentioned in the devicetree # files, with a regex dt_compats_search = re.compile( "|".join(re.escape(compat) for compat in dt_compats) ).search for binding_path in self._binding_paths: with open(binding_path, encoding="utf-8") as f: contents = f.read() # As an optimization, skip parsing files that don't contain any of # the .dts 'compatible' strings, which should be reasonably safe if not dt_compats_search(contents): continue # Load the binding and check that it actually matches one of the # compatibles. Might get false positives above due to comments and # stuff. try: # Parsed PyYAML output (Python lists/dictionaries/strings/etc., # representing the file) raw = yaml.load(contents, Loader=_BindingLoader) except yaml.YAMLError as e: _err( f"'{binding_path}' appears in binding directories " f"but isn't valid YAML: {e}") continue # Convert the raw data to a Binding object, erroring out # if necessary. binding = self._binding(raw, binding_path, dt_compats) # Register the binding in self._compat2binding, along with # any child bindings that have their own compatibles. while binding is not None: if binding.compatible: self._register_binding(binding) binding = binding.child_binding def _binding(self, raw: Optional[dict], binding_path: str, dt_compats: Set[str]) -> Optional[Binding]: # Convert a 'raw' binding from YAML to a Binding object and return it. # # Error out if the raw data looks like an invalid binding. # # Return None if the file doesn't contain a binding or the # binding's compatible isn't in dt_compats. # Get the 'compatible:' string. if raw is None or "compatible" not in raw: # Empty file, binding fragment, spurious file, etc. return None compatible = raw["compatible"] if compatible not in dt_compats: # Not a compatible we care about. return None # Initialize and return the Binding object. return Binding(binding_path, self._binding_fname2path, raw=raw) def _register_binding(self, binding: Binding) -> None: # Do not allow two different bindings to have the same # 'compatible:'/'on-bus:' combo if TYPE_CHECKING: assert binding.compatible old_binding = self._compat2binding.get((binding.compatible, binding.on_bus)) if old_binding: msg = (f"both {old_binding.path} and {binding.path} have " f"'compatible: {binding.compatible}'") if binding.on_bus is not None: msg += f" and 'on-bus: {binding.on_bus}'" _err(msg) # Register the binding. self._compat2binding[binding.compatible, binding.on_bus] = binding def _init_nodes(self) -> None: # Creates a list of edtlib.Node objects from the dtlib.Node objects, in # self.nodes for dt_node in self._dt.node_iter(): # Warning: We depend on parent Nodes being created before their # children. This is guaranteed by node_iter(). if "compatible" in dt_node.props: compats = dt_node.props["compatible"].to_strings() else: compats = [] node = Node(dt_node, self, compats) node.bus_node = node._bus_node(self._fixed_partitions_no_bus) node._init_binding() node._init_regs() node._init_ranges() self.nodes.append(node) self._node2enode[dt_node] = node for node in self.nodes: # These depend on all Node objects having been created, because # they (either always or sometimes) reference other nodes, so we # run them separately node._init_props(default_prop_types=self._default_prop_types, err_on_deprecated=self._werror) node._init_interrupts() node._init_pinctrls() if self._warn_reg_unit_address_mismatch: # This warning matches the simple_bus_reg warning in dtc for node in self.nodes: # Address mismatch is ok for PCI devices if (node.regs and node.regs[0].addr != node.unit_addr and not node.is_pci_device): _LOG.warning("unit address and first address in 'reg' " f"(0x{node.regs[0].addr:x}) don't match for " f"{node.path}") def _init_luts(self) -> None: # Initialize node lookup tables (LUTs). for node in self.nodes: for label in node.labels: self.label2node[label] = node for compat in node.compats: self.compat2nodes[compat].append(node) if node.status == "okay": self.compat2okay[compat].append(node) if compat in self.compat2vendor: continue # The regular expression comes from dt-schema. compat_re = r'^[a-zA-Z][a-zA-Z0-9,+\-._]+$' if not re.match(compat_re, compat): _err(f"node '{node.path}' compatible '{compat}' " 'must match this regular expression: ' f"'{compat_re}'") if ',' in compat and self._vendor_prefixes: vendor, model = compat.split(',', 1) if vendor in self._vendor_prefixes: self.compat2vendor[compat] = self._vendor_prefixes[vendor] self.compat2model[compat] = model # As an exception, the root node can have whatever # compatibles it wants. Other nodes get checked. elif node.path != '/': if self._werror: handler_fn: Any = _err else: handler_fn = _LOG.warning handler_fn( f"node '{node.path}' compatible '{compat}' " f"has unknown vendor prefix '{vendor}'") for nodeset in self.scc_order: node = nodeset[0] self.dep_ord2node[node.dep_ordinal] = node def _check(self) -> None: # Tree-wide checks and warnings. for binding in self._compat2binding.values(): for spec in binding.prop2specs.values(): if not spec.enum or spec.type != 'string': continue if not spec.enum_tokenizable: _LOG.warning( f"compatible '{binding.compatible}' " f"in binding '{binding.path}' has non-tokenizable enum " f"for property '{spec.name}': " + ', '.join(repr(x) for x in spec.enum)) elif not spec.enum_upper_tokenizable: _LOG.warning( f"compatible '{binding.compatible}' " f"in binding '{binding.path}' has enum for property " f"'{spec.name}' that is only tokenizable " 'in lowercase: ' + ', '.join(repr(x) for x in spec.enum)) # Validate the contents of compatible properties. for node in self.nodes: if 'compatible' not in node.props: continue compatibles = node.props['compatible'].val # _check() runs after _init_compat2binding() has called # _dt_compats(), which already converted every compatible # property to a list of strings. So we know 'compatibles' # is a list, but add an assert for future-proofing. assert isinstance(compatibles, list) for compat in compatibles: # This is also just for future-proofing. assert isinstance(compat, str) def bindings_from_paths(yaml_paths: List[str], ignore_errors: bool = False) -> List[Binding]: """ Get a list of Binding objects from the yaml files 'yaml_paths'. If 'ignore_errors' is True, YAML files that cause an EDTError when loaded are ignored. (No other exception types are silenced.) """ ret = [] fname2path = {os.path.basename(path): path for path in yaml_paths} for path in yaml_paths: try: ret.append(Binding(path, fname2path)) except EDTError: if ignore_errors: continue raise return ret class EDTError(Exception): "Exception raised for devicetree- and binding-related errors" # # Public global functions # def load_vendor_prefixes_txt(vendor_prefixes: str) -> Dict[str, str]: """Load a vendor-prefixes.txt file and return a dict representation mapping a vendor prefix to the vendor name. """ vnd2vendor: Dict[str, str] = {} with open(vendor_prefixes, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line or line.startswith('#'): # Comment or empty line. continue # Other lines should be in this form: # # <vnd><TAB><vendor> vnd_vendor = line.split('\t', 1) assert len(vnd_vendor) == 2, line vnd2vendor[vnd_vendor[0]] = vnd_vendor[1] return vnd2vendor # # Private global functions # def _dt_compats(dt: DT) -> Set[str]: # Returns a set() with all 'compatible' strings in the devicetree # represented by dt (a dtlib.DT instance) return {compat for node in dt.node_iter() if "compatible" in node.props for compat in node.props["compatible"].to_strings()} def _binding_paths(bindings_dirs: List[str]) -> List[str]: # Returns a list with the paths to all bindings (.yaml files) in # 'bindings_dirs' binding_paths = [] for bindings_dir in bindings_dirs: for root, _, filenames in os.walk(bindings_dir): for filename in filenames: if filename.endswith(".yaml") or filename.endswith(".yml"): binding_paths.append(os.path.join(root, filename)) return binding_paths def _binding_inc_error(msg): # Helper for reporting errors in the !include implementation raise yaml.constructor.ConstructorError(None, None, "error: " + msg) def _check_include_dict(name: Optional[str], allowlist: Optional[List[str]], blocklist: Optional[List[str]], child_filter: Optional[dict], binding_path: Optional[str]) -> None: # Check that an 'include:' named 'name' with property-allowlist # 'allowlist', property-blocklist 'blocklist', and # child-binding filter 'child_filter' has valid structure. if name is None: _err(f"'include:' element in {binding_path} " "should have a 'name' key") if allowlist is not None and blocklist is not None: _err(f"'include:' of file '{name}' in {binding_path} " "should not specify both 'property-allowlist:' " "and 'property-blocklist:'") while child_filter is not None: child_copy = deepcopy(child_filter) child_allowlist: Optional[List[str]] = \ child_copy.pop('property-allowlist', None) child_blocklist: Optional[List[str]] = \ child_copy.pop('property-blocklist', None) next_child_filter: Optional[dict] = \ child_copy.pop('child-binding', None) if child_copy: # We've popped out all the valid keys. _err(f"'include:' of file '{name}' in {binding_path} " "should not have these unexpected contents in a " f"'child-binding': {child_copy}") if child_allowlist is not None and child_blocklist is not None: _err(f"'include:' of file '{name}' in {binding_path} " "should not specify both 'property-allowlist:' and " "'property-blocklist:' in a 'child-binding:'") child_filter = next_child_filter def _filter_properties(raw: dict, allowlist: Optional[List[str]], blocklist: Optional[List[str]], child_filter: Optional[dict], binding_path: Optional[str]) -> None: # Destructively modifies 'raw["properties"]' and # 'raw["child-binding"]', if they exist, according to # 'allowlist', 'blocklist', and 'child_filter'. props = raw.get('properties') _filter_properties_helper(props, allowlist, blocklist, binding_path) child_binding = raw.get('child-binding') while child_filter is not None and child_binding is not None: _filter_properties_helper(child_binding.get('properties'), child_filter.get('property-allowlist'), child_filter.get('property-blocklist'), binding_path) child_filter = child_filter.get('child-binding') child_binding = child_binding.get('child-binding') def _filter_properties_helper(props: Optional[dict], allowlist: Optional[List[str]], blocklist: Optional[List[str]], binding_path: Optional[str]) -> None: if props is None or (allowlist is None and blocklist is None): return _check_prop_filter('property-allowlist', allowlist, binding_path) _check_prop_filter('property-blocklist', blocklist, binding_path) if allowlist is not None: allowset = set(allowlist) to_del = [prop for prop in props if prop not in allowset] else: if TYPE_CHECKING: assert blocklist blockset = set(blocklist) to_del = [prop for prop in props if prop in blockset] for prop in to_del: del props[prop] def _check_prop_filter(name: str, value: Optional[List[str]], binding_path: Optional[str]) -> None: # Ensure an include: ... property-allowlist or property-blocklist # is a list. if value is None: return if not isinstance(value, list): _err(f"'{name}' value {value} in {binding_path} should be a list") def _merge_props(to_dict: dict, from_dict: dict, parent: Optional[str], binding_path: Optional[str], check_required: bool = False): # Recursively merges 'from_dict' into 'to_dict', to implement 'include:'. # # If 'from_dict' and 'to_dict' contain a 'required:' key for the same # property, then the values are ORed together. # # If 'check_required' is True, then an error is raised if 'from_dict' has # 'required: true' while 'to_dict' has 'required: false'. This prevents # bindings from "downgrading" requirements from bindings they include, # which might help keep bindings well-organized. # # It's an error for most other keys to appear in both 'from_dict' and # 'to_dict'. When it's not an error, the value in 'to_dict' takes # precedence. # # 'parent' is the name of the parent key containing 'to_dict' and # 'from_dict', and 'binding_path' is the path to the top-level binding. # These are used to generate errors for sketchy property overwrites. for prop in from_dict: if isinstance(to_dict.get(prop), dict) and \ isinstance(from_dict[prop], dict): _merge_props(to_dict[prop], from_dict[prop], prop, binding_path, check_required) elif prop not in to_dict: to_dict[prop] = from_dict[prop] elif _bad_overwrite(to_dict, from_dict, prop, check_required): _err(f"{binding_path} (in '{parent}'): '{prop}' " f"from included file overwritten ('{from_dict[prop]}' " f"replaced with '{to_dict[prop]}')") elif prop == "required": # Need a separate check here, because this code runs before # Binding._check() if not (isinstance(from_dict["required"], bool) and isinstance(to_dict["required"], bool)): _err(f"malformed 'required:' setting for '{parent}' in " f"'properties' in {binding_path}, expected true/false") # 'required: true' takes precedence to_dict["required"] = to_dict["required"] or from_dict["required"] def _bad_overwrite(to_dict: dict, from_dict: dict, prop: str, check_required: bool) -> bool: # _merge_props() helper. Returns True in cases where it's bad that # to_dict[prop] takes precedence over from_dict[prop]. if to_dict[prop] == from_dict[prop]: return False # These are overridden deliberately if prop in {"title", "description", "compatible"}: return False if prop == "required": if not check_required: return False return from_dict[prop] and not to_dict[prop] return True def _binding_include(loader, node): # Implements !include, for backwards compatibility. '!include [foo, bar]' # just becomes [foo, bar]. if isinstance(node, yaml.ScalarNode): # !include foo.yaml return [loader.construct_scalar(node)] if isinstance(node, yaml.SequenceNode): # !include [foo.yaml, bar.yaml] return loader.construct_sequence(node) _binding_inc_error("unrecognised node type in !include statement") def _check_prop_by_type(prop_name: str, options: dict, binding_path: Optional[str]) -> None: # Binding._check_properties() helper. Checks 'type:', 'default:', # 'const:' and # 'specifier-space:' for the property named 'prop_name' prop_type = options.get("type") default = options.get("default") const = options.get("const") if prop_type is None: _err(f"missing 'type:' for '{prop_name}' in 'properties' in " f"{binding_path}") ok_types = {"boolean", "int", "array", "uint8-array", "string", "string-array", "phandle", "phandles", "phandle-array", "path", "compound"} if prop_type not in ok_types: _err(f"'{prop_name}' in 'properties:' in {binding_path} " f"has unknown type '{prop_type}', expected one of " + ", ".join(ok_types)) if "specifier-space" in options and prop_type != "phandle-array": _err(f"'specifier-space' in 'properties: {prop_name}' " f"has type '{prop_type}', expected 'phandle-array'") if prop_type == "phandle-array": if not prop_name.endswith("s") and not "specifier-space" in options: _err(f"'{prop_name}' in 'properties:' in {binding_path} " f"has type 'phandle-array' and its name does not end in 's', " f"but no 'specifier-space' was provided.") # If you change const_types, be sure to update the type annotation # for PropertySpec.const. const_types = {"int", "array", "uint8-array", "string", "string-array"} if const and prop_type not in const_types: _err(f"const in {binding_path} for property '{prop_name}' " f"has type '{prop_type}', expected one of " + ", ".join(const_types)) # Check default if default is None: return if prop_type in {"boolean", "compound", "phandle", "phandles", "phandle-array", "path"}: _err("'default:' can't be combined with " f"'type: {prop_type}' for '{prop_name}' in " f"'properties:' in {binding_path}") def ok_default() -> bool: # Returns True if 'default' is an okay default for the property's type. # If you change this, be sure to update the type annotation for # PropertySpec.default. if prop_type == "int" and isinstance(default, int) or \ prop_type == "string" and isinstance(default, str): return True # array, uint8-array, or string-array if not isinstance(default, list): return False if prop_type == "array" and \ all(isinstance(val, int) for val in default): return True if prop_type == "uint8-array" and \ all(isinstance(val, int) and 0 <= val <= 255 for val in default): return True # string-array return all(isinstance(val, str) for val in default) if not ok_default(): _err(f"'default: {default}' is invalid for '{prop_name}' " f"in 'properties:' in {binding_path}, " f"which has type {prop_type}") def _translate(addr: int, node: dtlib_Node) -> int: # Recursively translates 'addr' on 'node' to the address space(s) of its # parent(s), by looking at 'ranges' properties. Returns the translated # address. if not node.parent or "ranges" not in node.parent.props: # No translation return addr if not node.parent.props["ranges"].value: # DT spec.: "If the property is defined with an <empty> value, it # specifies that the parent and child address space is identical, and # no address translation is required." # # Treat this the same as a 'range' that explicitly does a one-to-one # mapping, as opposed to there not being any translation. return _translate(addr, node.parent) # Gives the size of each component in a translation 3-tuple in 'ranges' child_address_cells = _address_cells(node) parent_address_cells = _address_cells(node.parent) child_size_cells = _size_cells(node) # Number of cells for one translation 3-tuple in 'ranges' entry_cells = child_address_cells + parent_address_cells + child_size_cells for raw_range in _slice(node.parent, "ranges", 4*entry_cells, f"4*(<#address-cells> (= {child_address_cells}) + " "<#address-cells for parent> " f"(= {parent_address_cells}) + " f"<#size-cells> (= {child_size_cells}))"): child_addr = to_num(raw_range[:4*child_address_cells]) raw_range = raw_range[4*child_address_cells:] parent_addr = to_num(raw_range[:4*parent_address_cells]) raw_range = raw_range[4*parent_address_cells:] child_len = to_num(raw_range) if child_addr <= addr < child_addr + child_len: # 'addr' is within range of a translation in 'ranges'. Recursively # translate it and return the result. return _translate(parent_addr + addr - child_addr, node.parent) # 'addr' is not within range of any translation in 'ranges' return addr def _add_names(node: dtlib_Node, names_ident: str, objs: Any) -> None: # Helper for registering names from <foo>-names properties. # # node: # Node which has a property that might need named elements. # # names-ident: # The <foo> part of <foo>-names, e.g. "reg" for "reg-names" # # objs: # list of objects whose .name field should be set full_names_ident = names_ident + "-names" if full_names_ident in node.props: names = node.props[full_names_ident].to_strings() if len(names) != len(objs): _err(f"{full_names_ident} property in {node.path} " f"in {node.dt.filename} has {len(names)} strings, " f"expected {len(objs)} strings") for obj, name in zip(objs, names): if obj is None: continue obj.name = name else: for obj in objs: if obj is not None: obj.name = None def _interrupt_parent(start_node: dtlib_Node) -> dtlib_Node: # Returns the node pointed at by the closest 'interrupt-parent', searching # the parents of 'node'. As of writing, this behavior isn't specified in # the DT spec., but seems to match what some .dts files except. node: Optional[dtlib_Node] = start_node while node: if "interrupt-parent" in node.props: return node.props["interrupt-parent"].to_node() node = node.parent _err(f"{start_node!r} has an 'interrupts' property, but neither the node " f"nor any of its parents has an 'interrupt-parent' property") def _interrupts(node: dtlib_Node) -> List[Tuple[dtlib_Node, bytes]]: # Returns a list of (<controller>, <data>) tuples, with one tuple per # interrupt generated by 'node'. <controller> is the destination of the # interrupt (possibly after mapping through an 'interrupt-map'), and <data> # the data associated with the interrupt (as a 'bytes' object). # Takes precedence over 'interrupts' if both are present if "interrupts-extended" in node.props: prop = node.props["interrupts-extended"] ret: List[Tuple[dtlib_Node, bytes]] = [] for entry in _phandle_val_list(prop, "interrupt"): if entry is None: _err(f"node '{node.path}' interrupts-extended property " "has an empty element") iparent, spec = entry ret.append(_map_interrupt(node, iparent, spec)) return ret if "interrupts" in node.props: # Treat 'interrupts' as a special case of 'interrupts-extended', with # the same interrupt parent for all interrupts iparent = _interrupt_parent(node) interrupt_cells = _interrupt_cells(iparent) return [_map_interrupt(node, iparent, raw) for raw in _slice(node, "interrupts", 4*interrupt_cells, "4*<#interrupt-cells>")] return [] def _map_interrupt( child: dtlib_Node, parent: dtlib_Node, child_spec: bytes ) -> Tuple[dtlib_Node, bytes]: # Translates an interrupt headed from 'child' to 'parent' with data # 'child_spec' through any 'interrupt-map' properties. Returns a # (<controller>, <data>) tuple with the final destination after mapping. if "interrupt-controller" in parent.props: return (parent, child_spec) def own_address_cells(node): # Used for parents pointed at by 'interrupt-map'. We can't use # _address_cells(), because it's the #address-cells property on 'node' # itself that matters. address_cells = node.props.get("#address-cells") if not address_cells: _err(f"missing #address-cells on {node!r} " "(while handling interrupt-map)") return address_cells.to_num() def spec_len_fn(node): # Can't use _address_cells() here, because it's the #address-cells # property on 'node' itself that matters return own_address_cells(node) + _interrupt_cells(node) parent, raw_spec = _map( "interrupt", child, parent, _raw_unit_addr(child) + child_spec, spec_len_fn, require_controller=True) # Strip the parent unit address part, if any return (parent, raw_spec[4*own_address_cells(parent):]) def _map_phandle_array_entry( child: dtlib_Node, parent: dtlib_Node, child_spec: bytes, basename: str ) -> Tuple[dtlib_Node, bytes]: # Returns a (<controller>, <data>) tuple with the final destination after # mapping through any '<basename>-map' (e.g. gpio-map) properties. See # _map_interrupt(). def spec_len_fn(node): prop_name = f"#{basename}-cells" if prop_name not in node.props: _err(f"expected '{prop_name}' property on {node!r} " f"(referenced by {child!r})") return node.props[prop_name].to_num() # Do not require <prefix>-controller for anything but interrupts for now return _map(basename, child, parent, child_spec, spec_len_fn, require_controller=False) def _map( prefix: str, child: dtlib_Node, parent: dtlib_Node, child_spec: bytes, spec_len_fn: Callable[[dtlib_Node], int], require_controller: bool ) -> Tuple[dtlib_Node, bytes]: # Common code for mapping through <prefix>-map properties, e.g. # interrupt-map and gpio-map. # # prefix: # The prefix, e.g. "interrupt" or "gpio" # # child: # The "sender", e.g. the node with 'interrupts = <...>' # # parent: # The "receiver", e.g. a node with 'interrupt-map = <...>' or # 'interrupt-controller' (no mapping) # # child_spec: # The data associated with the interrupt/GPIO/etc., as a 'bytes' object, # e.g. <1 2> for 'foo-gpios = <&gpio1 1 2>'. # # spec_len_fn: # Function called on a parent specified in a *-map property to get the # length of the parent specifier (data after phandle in *-map), in cells # # require_controller: # If True, the final controller node after mapping is required to have # to have a <prefix>-controller property. map_prop = parent.props.get(prefix + "-map") if not map_prop: if require_controller and prefix + "-controller" not in parent.props: _err(f"expected '{prefix}-controller' property on {parent!r} " f"(referenced by {child!r})") # No mapping return (parent, child_spec) masked_child_spec = _mask(prefix, child, parent, child_spec) raw = map_prop.value while raw: if len(raw) < len(child_spec): _err(f"bad value for {map_prop!r}, missing/truncated child data") child_spec_entry = raw[:len(child_spec)] raw = raw[len(child_spec):] if len(raw) < 4: _err(f"bad value for {map_prop!r}, missing/truncated phandle") phandle = to_num(raw[:4]) raw = raw[4:] # Parent specified in *-map map_parent = parent.dt.phandle2node.get(phandle) if not map_parent: _err(f"bad phandle ({phandle}) in {map_prop!r}") map_parent_spec_len = 4*spec_len_fn(map_parent) if len(raw) < map_parent_spec_len: _err(f"bad value for {map_prop!r}, missing/truncated parent data") parent_spec = raw[:map_parent_spec_len] raw = raw[map_parent_spec_len:] # Got one *-map row. Check if it matches the child data. if child_spec_entry == masked_child_spec: # Handle *-map-pass-thru parent_spec = _pass_thru( prefix, child, parent, child_spec, parent_spec) # Found match. Recursively map and return it. return _map(prefix, parent, map_parent, parent_spec, spec_len_fn, require_controller) _err(f"child specifier for {child!r} ({child_spec!r}) " f"does not appear in {map_prop!r}") def _mask( prefix: str, child: dtlib_Node, parent: dtlib_Node, child_spec: bytes ) -> bytes: # Common code for handling <prefix>-mask properties, e.g. interrupt-mask. # See _map() for the parameters. mask_prop = parent.props.get(prefix + "-map-mask") if not mask_prop: # No mask return child_spec mask = mask_prop.value if len(mask) != len(child_spec): _err(f"{child!r}: expected '{prefix}-mask' in {parent!r} " f"to be {len(child_spec)} bytes, is {len(mask)} bytes") return _and(child_spec, mask) def _pass_thru( prefix: str, child: dtlib_Node, parent: dtlib_Node, child_spec: bytes, parent_spec: bytes ) -> bytes: # Common code for handling <prefix>-map-thru properties, e.g. # interrupt-pass-thru. # # parent_spec: # The parent data from the matched entry in the <prefix>-map property # # See _map() for the other parameters. pass_thru_prop = parent.props.get(prefix + "-map-pass-thru") if not pass_thru_prop: # No pass-thru return parent_spec pass_thru = pass_thru_prop.value if len(pass_thru) != len(child_spec): _err(f"{child!r}: expected '{prefix}-map-pass-thru' in {parent!r} " f"to be {len(child_spec)} bytes, is {len(pass_thru)} bytes") res = _or(_and(child_spec, pass_thru), _and(parent_spec, _not(pass_thru))) # Truncate to length of parent spec. return res[-len(parent_spec):] def _raw_unit_addr(node: dtlib_Node) -> bytes: # _map_interrupt() helper. Returns the unit address (derived from 'reg' and # #address-cells) as a raw 'bytes' if 'reg' not in node.props: _err(f"{node!r} lacks 'reg' property " "(needed for 'interrupt-map' unit address lookup)") addr_len = 4*_address_cells(node) if len(node.props['reg'].value) < addr_len: _err(f"{node!r} has too short 'reg' property " "(while doing 'interrupt-map' unit address lookup)") return node.props['reg'].value[:addr_len] def _and(b1: bytes, b2: bytes) -> bytes: # Returns the bitwise AND of the two 'bytes' objects b1 and b2. Pads # with ones on the left if the lengths are not equal. # Pad on the left, to equal length maxlen = max(len(b1), len(b2)) return bytes(x & y for x, y in zip(b1.rjust(maxlen, b'\xff'), b2.rjust(maxlen, b'\xff'))) def _or(b1: bytes, b2: bytes) -> bytes: # Returns the bitwise OR of the two 'bytes' objects b1 and b2. Pads with # zeros on the left if the lengths are not equal. # Pad on the left, to equal length maxlen = max(len(b1), len(b2)) return bytes(x | y for x, y in zip(b1.rjust(maxlen, b'\x00'), b2.rjust(maxlen, b'\x00'))) def _not(b: bytes) -> bytes: # Returns the bitwise not of the 'bytes' object 'b' # ANDing with 0xFF avoids negative numbers return bytes(~x & 0xFF for x in b) def _phandle_val_list( prop: dtlib_Property, n_cells_name: str ) -> List[Optional[Tuple[dtlib_Node, bytes]]]: # Parses a '<phandle> <value> <phandle> <value> ...' value. The number of # cells that make up each <value> is derived from the node pointed at by # the preceding <phandle>. # # prop: # dtlib.Property with value to parse # # n_cells_name: # The <name> part of the #<name>-cells property to look for on the nodes # the phandles point to, e.g. "gpio" for #gpio-cells. # # Each tuple in the return value is a (<node>, <value>) pair, where <node> # is the node pointed at by <phandle>. If <phandle> does not refer # to a node, the entire list element is None. full_n_cells_name = f"#{n_cells_name}-cells" res: List[Optional[Tuple[dtlib_Node, bytes]]] = [] raw = prop.value while raw: if len(raw) < 4: # Not enough room for phandle _err("bad value for " + repr(prop)) phandle = to_num(raw[:4]) raw = raw[4:] node = prop.node.dt.phandle2node.get(phandle) if not node: # Unspecified phandle-array element. This is valid; a 0 # phandle value followed by no cells is an empty element. res.append(None) continue if full_n_cells_name not in node.props: _err(f"{node!r} lacks {full_n_cells_name}") n_cells = node.props[full_n_cells_name].to_num() if len(raw) < 4*n_cells: _err("missing data after phandle in " + repr(prop)) res.append((node, raw[:4*n_cells])) raw = raw[4*n_cells:] return res def _address_cells(node: dtlib_Node) -> int: # Returns the #address-cells setting for 'node', giving the number of <u32> # cells used to encode the address in the 'reg' property if TYPE_CHECKING: assert node.parent if "#address-cells" in node.parent.props: return node.parent.props["#address-cells"].to_num() return 2 # Default value per DT spec. def _size_cells(node: dtlib_Node) -> int: # Returns the #size-cells setting for 'node', giving the number of <u32> # cells used to encode the size in the 'reg' property if TYPE_CHECKING: assert node.parent if "#size-cells" in node.parent.props: return node.parent.props["#size-cells"].to_num() return 1 # Default value per DT spec. def _interrupt_cells(node: dtlib_Node) -> int: # Returns the #interrupt-cells property value on 'node', erroring out if # 'node' has no #interrupt-cells property if "#interrupt-cells" not in node.props: _err(f"{node!r} lacks #interrupt-cells") return node.props["#interrupt-cells"].to_num() def _slice(node: dtlib_Node, prop_name: str, size: int, size_hint: str) -> List[bytes]: return _slice_helper(node, prop_name, size, size_hint, EDTError) def _check_dt(dt: DT) -> None: # Does devicetree sanity checks. dtlib is meant to be general and # anything-goes except for very special properties like phandle, but in # edtlib we can be pickier. # Check that 'status' has one of the values given in the devicetree spec. # Accept "ok" for backwards compatibility ok_status = {"ok", "okay", "disabled", "reserved", "fail", "fail-sss"} for node in dt.node_iter(): if "status" in node.props: try: status_val = node.props["status"].to_string() except DTError as e: # The error message gives the path _err(str(e)) if status_val not in ok_status: _err(f"unknown 'status' value \"{status_val}\" in {node.path} " f"in {node.dt.filename}, expected one of " + ", ".join(ok_status) + " (see the devicetree specification)") ranges_prop = node.props.get("ranges") if ranges_prop: if ranges_prop.type not in (Type.EMPTY, Type.NUMS): _err(f"expected 'ranges = < ... >;' in {node.path} in " f"{node.dt.filename}, not '{ranges_prop}' " "(see the devicetree specification)") def _err(msg) -> NoReturn: raise EDTError(msg) # Logging object _LOG = logging.getLogger(__name__) # Regular expression for non-alphanumeric-or-underscore characters. _NOT_ALPHANUM_OR_UNDERSCORE = re.compile(r'\W', re.ASCII) def str_as_token(val: str) -> str: """Return a canonical representation of a string as a C token. This converts special characters in 'val' to underscores, and returns the result.""" return re.sub(_NOT_ALPHANUM_OR_UNDERSCORE, '_', val) # Custom PyYAML binding loader class to avoid modifying yaml.Loader directly, # which could interfere with YAML loading in clients class _BindingLoader(Loader): pass # Add legacy '!include foo.yaml' handling _BindingLoader.add_constructor("!include", _binding_include) # # "Default" binding for properties which are defined by the spec. # # Zephyr: do not change the _DEFAULT_PROP_TYPES keys without # updating the documentation for the DT_PROP() macro in # include/devicetree.h. # _DEFAULT_PROP_TYPES: Dict[str, str] = { "compatible": "string-array", "status": "string", "ranges": "compound", # NUMS or EMPTY "reg": "array", "reg-names": "string-array", "label": "string", "interrupts": "array", "interrupts-extended": "compound", "interrupt-names": "string-array", "interrupt-controller": "boolean", } _STATUS_ENUM: List[str] = "ok okay disabled reserved fail fail-sss".split() def _raw_default_property_for( name: str ) -> Dict[str, Union[str, bool, List[str]]]: ret: Dict[str, Union[str, bool, List[str]]] = { 'type': _DEFAULT_PROP_TYPES[name], 'required': False, } if name == 'status': ret['enum'] = _STATUS_ENUM return ret _DEFAULT_PROP_BINDING: Binding = Binding( None, {}, raw={ 'properties': { name: _raw_default_property_for(name) for name in _DEFAULT_PROP_TYPES }, }, require_compatible=False, require_description=False, ) _DEFAULT_PROP_SPECS: Dict[str, PropertySpec] = { name: PropertySpec(name, _DEFAULT_PROP_BINDING) for name in _DEFAULT_PROP_TYPES } ```
/content/code_sandbox/scripts/dts/python-devicetree/src/devicetree/edtlib.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
27,638
```python # from __future__ import annotations import logging import os if os.name != 'nt': import pty import re import subprocess import time from pathlib import Path import serial from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.exceptions import ( TwisterHarnessException, TwisterHarnessTimeoutException, ) from twister_harness.device.utils import log_command, terminate_process from twister_harness.twister_harness_config import DeviceConfig logger = logging.getLogger(__name__) class HardwareAdapter(DeviceAdapter): """Adapter class for real device.""" def __init__(self, device_config: DeviceConfig) -> None: super().__init__(device_config) self._flashing_timeout: float = self.base_timeout self._serial_connection: serial.Serial | None = None self._serial_pty_proc: subprocess.Popen | None = None self._serial_buffer: bytearray = bytearray() self.device_log_path: Path = device_config.build_dir / 'device.log' self._log_files.append(self.device_log_path) def generate_command(self) -> None: """Return command to flash.""" command = [ self.west, 'flash', '--skip-rebuild', '--build-dir', str(self.device_config.build_dir), ] command_extra_args = [] if self.device_config.west_flash_extra_args: command_extra_args.extend(self.device_config.west_flash_extra_args) if self.device_config.runner: runner_base_args, runner_extra_args = self._prepare_runner_args() command.extend(runner_base_args) command_extra_args.extend(runner_extra_args) if command_extra_args: command.append('--') command.extend(command_extra_args) self.command = command def _prepare_runner_args(self) -> tuple[list[str], list[str]]: base_args: list[str] = [] extra_args: list[str] = [] runner = self.device_config.runner base_args.extend(['--runner', runner]) if self.device_config.runner_params: for param in self.device_config.runner_params: extra_args.append(param) if board_id := self.device_config.id: if runner == 'pyocd': extra_args.append('--board-id') extra_args.append(board_id) elif runner in ('nrfjprog', 'nrfutil'): extra_args.append('--dev-id') extra_args.append(board_id) elif runner == 'openocd' and self.device_config.product in ['STM32 STLink', 'STLINK-V3']: extra_args.append('--cmd-pre-init') extra_args.append(f'hla_serial {board_id}') elif runner == 'openocd' and self.device_config.product == 'EDBG CMSIS-DAP': extra_args.append('--cmd-pre-init') extra_args.append(f'cmsis_dap_serial {board_id}') elif runner == "openocd" and self.device_config.product == "LPC-LINK2 CMSIS-DAP": extra_args.append("--cmd-pre-init") extra_args.append(f'adapter serial {board_id}') elif runner == 'jlink': base_args.append(f'--dev-id {board_id}') elif runner == 'stm32cubeprogrammer': base_args.append(f'--tool-opt=sn={board_id}') elif runner == 'linkserver': base_args.append(f'--probe={board_id}') return base_args, extra_args def _flash_and_run(self) -> None: """Flash application on a device.""" if not self.command: msg = 'Flash command is empty, please verify if it was generated properly.' logger.error(msg) raise TwisterHarnessException(msg) if self.device_config.pre_script: self._run_custom_script(self.device_config.pre_script, self.base_timeout) if self.device_config.id: logger.debug('Flashing device %s', self.device_config.id) log_command(logger, 'Flashing command', self.command, level=logging.DEBUG) process = stdout = None try: process = subprocess.Popen(self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=self.env) stdout, _ = process.communicate(timeout=self._flashing_timeout) except subprocess.TimeoutExpired as exc: process.kill() msg = f'Timeout occurred ({self._flashing_timeout}s) during flashing.' logger.error(msg) raise TwisterHarnessTimeoutException(msg) from exc except subprocess.SubprocessError as exc: msg = f'Flashing subprocess failed due to SubprocessError {exc}' logger.error(msg) raise TwisterHarnessTimeoutException(msg) from exc finally: if stdout is not None: stdout_decoded = stdout.decode(errors='ignore') with open(self.device_log_path, 'a+') as log_file: log_file.write(stdout_decoded) if self.device_config.post_flash_script: self._run_custom_script(self.device_config.post_flash_script, self.base_timeout) if process is not None and process.returncode == 0: logger.debug('Flashing finished') else: msg = f'Could not flash device {self.device_config.id}' logger.error(msg) raise TwisterHarnessException(msg) def _connect_device(self) -> None: serial_name = self._open_serial_pty() or self.device_config.serial logger.debug('Opening serial connection for %s', serial_name) try: self._serial_connection = serial.Serial( serial_name, baudrate=self.device_config.baud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.base_timeout, ) except serial.SerialException as exc: logger.exception('Cannot open connection: %s', exc) self._close_serial_pty() raise self._serial_connection.flush() self._serial_connection.reset_input_buffer() self._serial_connection.reset_output_buffer() def _open_serial_pty(self) -> str | None: """Open a pty pair, run process and return tty name""" if not self.device_config.serial_pty: return None try: master, slave = pty.openpty() except NameError as exc: logger.exception('PTY module is not available.') raise exc try: self._serial_pty_proc = subprocess.Popen( re.split(',| ', self.device_config.serial_pty), stdout=master, stdin=master, stderr=master ) except subprocess.CalledProcessError as exc: logger.exception('Failed to run subprocess %s, error %s', self.device_config.serial_pty, str(exc)) raise return os.ttyname(slave) def _disconnect_device(self) -> None: if self._serial_connection: serial_name = self._serial_connection.port self._serial_connection.close() # self._serial_connection = None logger.debug('Closed serial connection for %s', serial_name) self._close_serial_pty() def _close_serial_pty(self) -> None: """Terminate the process opened for serial pty script""" if self._serial_pty_proc: self._serial_pty_proc.terminate() self._serial_pty_proc.communicate(timeout=self.base_timeout) logger.debug('Process %s terminated', self.device_config.serial_pty) self._serial_pty_proc = None def _close_device(self) -> None: if self.device_config.post_script: self._run_custom_script(self.device_config.post_script, self.base_timeout) def is_device_running(self) -> bool: return self._device_run.is_set() def is_device_connected(self) -> bool: return bool( self.is_device_running() and self._device_connected.is_set() and self._serial_connection and self._serial_connection.is_open ) def _read_device_output(self) -> bytes: try: output = self._readline_serial() except (serial.SerialException, TypeError, IOError): # serial was probably disconnected output = b'' return output def _readline_serial(self) -> bytes: """ This method was created to avoid using PySerial built-in readline method which cause blocking reader thread even if there is no data to read. Instead for this, following implementation try to read data only if they are available. Inspiration for this code was taken from this comment: path_to_url#issuecomment-369414522 """ line = self._readline_from_serial_buffer() if line is not None: return line while True: if self._serial_connection is None or not self._serial_connection.is_open: return b'' elif self._serial_connection.in_waiting == 0: time.sleep(0.05) continue else: bytes_to_read = max(1, min(2048, self._serial_connection.in_waiting)) output = self._serial_connection.read(bytes_to_read) self._serial_buffer.extend(output) line = self._readline_from_serial_buffer() if line is not None: return line def _readline_from_serial_buffer(self) -> bytes | None: idx = self._serial_buffer.find(b"\n") if idx >= 0: line = self._serial_buffer[:idx+1] self._serial_buffer = self._serial_buffer[idx+1:] return bytes(line) else: return None def _write_to_device(self, data: bytes) -> None: self._serial_connection.write(data) def _flush_device_output(self) -> None: if self.is_device_connected(): self._serial_connection.flush() self._serial_connection.reset_input_buffer() def _clear_internal_resources(self) -> None: super()._clear_internal_resources() self._serial_connection = None self._serial_pty_proc = None self._serial_buffer.clear() @staticmethod def _run_custom_script(script_path: str | Path, timeout: float) -> None: with subprocess.Popen(str(script_path), stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, stderr = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) if proc.returncode != 0: msg = f'Custom script failure: \n{stderr.decode(errors="ignore")}' logger.error(msg) raise TwisterHarnessException(msg) except subprocess.TimeoutExpired as exc: terminate_process(proc) proc.communicate(timeout=timeout) msg = f'Timeout occurred ({timeout}s) during execution custom script: {script_path}' logger.error(msg) raise TwisterHarnessTimeoutException(msg) from exc ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/hardware_adapter.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,297
```python # from __future__ import annotations import logging from typing import Type from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.device.hardware_adapter import HardwareAdapter from twister_harness.device.qemu_adapter import QemuAdapter from twister_harness.device.binary_adapter import ( CustomSimulatorAdapter, NativeSimulatorAdapter, UnitSimulatorAdapter, ) from twister_harness.exceptions import TwisterHarnessException logger = logging.getLogger(__name__) class DeviceFactory: _devices: dict[str, Type[DeviceAdapter]] = {} @classmethod def discover(cls): """Return available devices.""" @classmethod def register_device_class(cls, name: str, klass: Type[DeviceAdapter]): if name not in cls._devices: cls._devices[name] = klass @classmethod def get_device(cls, name: str) -> Type[DeviceAdapter]: logger.debug('Get device type "%s"', name) try: return cls._devices[name] except KeyError as exc: logger.error('There is no device with name "%s"', name) raise TwisterHarnessException(f'There is no device with name "{name}"') from exc DeviceFactory.register_device_class('custom', CustomSimulatorAdapter) DeviceFactory.register_device_class('native', NativeSimulatorAdapter) DeviceFactory.register_device_class('unit', UnitSimulatorAdapter) DeviceFactory.register_device_class('hardware', HardwareAdapter) DeviceFactory.register_device_class('qemu', QemuAdapter) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/factory.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
323
```python # from __future__ import annotations import abc import logging import subprocess from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.device.utils import log_command, terminate_process from twister_harness.exceptions import TwisterHarnessException from twister_harness.twister_harness_config import DeviceConfig logger = logging.getLogger(__name__) class BinaryAdapterBase(DeviceAdapter, abc.ABC): def __init__(self, device_config: DeviceConfig) -> None: """ :param twister_config: twister configuration """ super().__init__(device_config) self._process: subprocess.Popen | None = None self.process_kwargs: dict = { 'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT, 'stdin': subprocess.PIPE, 'env': self.env, 'cwd': device_config.app_build_dir, } @abc.abstractmethod def generate_command(self) -> None: """Generate and set command which will be used during running device.""" def _flash_and_run(self) -> None: self._run_subprocess() def _run_subprocess(self) -> None: if not self.command: msg = 'Run command is empty, please verify if it was generated properly.' logger.error(msg) raise TwisterHarnessException(msg) log_command(logger, 'Running command', self.command, level=logging.DEBUG) try: self._process = subprocess.Popen(self.command, **self.process_kwargs) except subprocess.SubprocessError as exc: msg = f'Running subprocess failed due to SubprocessError {exc}' logger.error(msg) raise TwisterHarnessException(msg) from exc except FileNotFoundError as exc: msg = f'Running subprocess failed due to file not found: {exc.filename}' logger.error(msg) raise TwisterHarnessException(msg) from exc except Exception as exc: msg = f'Running subprocess failed {exc}' logger.error(msg) raise TwisterHarnessException(msg) from exc def _connect_device(self) -> None: """ This method was implemented only to imitate standard connect behavior like in Serial class. """ def _disconnect_device(self) -> None: """ This method was implemented only to imitate standard disconnect behavior like in serial connection. """ def _close_device(self) -> None: """Terminate subprocess""" self._stop_subprocess() def _stop_subprocess(self) -> None: if self._process is None: # subprocess already stopped return return_code: int | None = self._process.poll() if return_code is None: terminate_process(self._process) return_code = self._process.wait(self.base_timeout) self._process = None logger.debug('Running subprocess finished with return code %s', return_code) def _read_device_output(self) -> bytes: return self._process.stdout.readline() def _write_to_device(self, data: bytes) -> None: self._process.stdin.write(data) self._process.stdin.flush() def _flush_device_output(self) -> None: if self.is_device_running(): self._process.stdout.flush() def is_device_running(self) -> bool: return self._device_run.is_set() and self._is_binary_running() def _is_binary_running(self) -> bool: if self._process is None or self._process.poll() is not None: return False return True def is_device_connected(self) -> bool: """Return true if device is connected.""" return self.is_device_running() and self._device_connected.is_set() def _clear_internal_resources(self) -> None: super()._clear_internal_resources() self._process = None class NativeSimulatorAdapter(BinaryAdapterBase): """Simulator adapter to run `zephyr.exe` simulation""" def generate_command(self) -> None: """Set command to run.""" self.command = [str(self.device_config.app_build_dir / 'zephyr' / 'zephyr.exe')] class UnitSimulatorAdapter(BinaryAdapterBase): """Simulator adapter to run unit tests""" def generate_command(self) -> None: """Set command to run.""" self.command = [str(self.device_config.app_build_dir / 'testbinary')] class CustomSimulatorAdapter(BinaryAdapterBase): def generate_command(self) -> None: """Set command to run.""" self.command = [self.west, 'build', '-d', str(self.device_config.app_build_dir), '-t', 'run'] ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/binary_adapter.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
977
```python # from __future__ import annotations import abc import logging import os import queue import re import shutil import threading import time from datetime import datetime from pathlib import Path from serial import SerialException from twister_harness.exceptions import ( TwisterHarnessException, TwisterHarnessTimeoutException, ) from twister_harness.twister_harness_config import DeviceConfig logger = logging.getLogger(__name__) class DeviceAdapter(abc.ABC): """ This class defines a common interface for all device types (hardware, simulator, QEMU) used in tests to gathering device output and send data to it. """ def __init__(self, device_config: DeviceConfig) -> None: """ :param device_config: device configuration """ self.device_config: DeviceConfig = device_config self.base_timeout: float = device_config.base_timeout self._device_read_queue: queue.Queue = queue.Queue() self._reader_thread: threading.Thread | None = None self._device_run: threading.Event = threading.Event() self._device_connected: threading.Event = threading.Event() self.command: list[str] = [] self._west: str | None = None self.handler_log_path: Path = device_config.build_dir / 'handler.log' self._log_files: list[Path] = [self.handler_log_path] def __repr__(self) -> str: return f'{self.__class__.__name__}()' @property def env(self) -> dict[str, str]: env = os.environ.copy() return env def launch(self) -> None: """ Start by closing previously running application (no effect if not needed). Then, flash and run test application. Finally, start an internal reader thread capturing an output from a device. """ self.close() self._clear_internal_resources() if not self.command: self.generate_command() if self.device_config.type != 'hardware': self._flash_and_run() self._device_run.set() self._start_reader_thread() self.connect() return self._device_run.set() self._start_reader_thread() if self.device_config.flash_before: # For hardware devices with shared USB or software USB, connect after flashing. # Retry for up to 10 seconds for USB-CDC based devices to enumerate. self._flash_and_run() self.connect(retry_s = 10) else: # On hardware, flash after connecting to COM port, otherwise some messages # from target can be lost. self.connect() self._flash_and_run() def close(self) -> None: """Disconnect, close device and close reader thread.""" if not self._device_run.is_set(): # device already closed return self.disconnect() self._close_device() self._device_run.clear() self._join_reader_thread() def connect(self, retry_s: int = 0) -> None: """Connect to device - allow for output gathering.""" if self.is_device_connected(): logger.debug('Device already connected') return if not self.is_device_running(): msg = 'Cannot connect to not working device' logger.error(msg) raise TwisterHarnessException(msg) if retry_s > 0: retry_cycles = retry_s * 10 for i in range(retry_cycles): try: self._connect_device() break except SerialException: if i == retry_cycles - 1: raise time.sleep(0.1) else: self._connect_device() self._device_connected.set() def disconnect(self) -> None: """Disconnect device - block output gathering.""" if not self.is_device_connected(): logger.debug("Device already disconnected") return self._disconnect_device() self._device_connected.clear() def readline(self, timeout: float | None = None, print_output: bool = True) -> str: """ Read line from device output. If timeout is not provided, then use base_timeout. """ timeout = timeout or self.base_timeout if self.is_device_connected() or not self._device_read_queue.empty(): data = self._read_from_queue(timeout) else: msg = 'No connection to the device and no more data to read.' logger.error(msg) raise TwisterHarnessException('No connection to the device and no more data to read.') if print_output: logger.debug('#: %s', data) return data def readlines_until( self, regex: str | None = None, num_of_lines: int | None = None, timeout: float | None = None, print_output: bool = True, ) -> list[str]: """ Read available output lines produced by device from internal buffer until following conditions: 1. If regex is provided - read until regex regex is found in read line (or until timeout). 2. If num_of_lines is provided - read until number of read lines is equal to num_of_lines (or until timeout). 3. If none of above is provided - return immediately lines collected so far in internal buffer. If timeout is not provided, then use base_timeout. """ timeout = timeout or self.base_timeout if regex: regex_compiled = re.compile(regex) lines: list[str] = [] if regex or num_of_lines: timeout_time: float = time.time() + timeout while time.time() < timeout_time: try: line = self.readline(0.1, print_output) except TwisterHarnessTimeoutException: continue lines.append(line) if regex and regex_compiled.search(line): break if num_of_lines and len(lines) == num_of_lines: break else: msg = 'Read from device timeout occurred' logger.error(msg) raise TwisterHarnessTimeoutException(msg) else: lines = self.readlines(print_output) return lines def readlines(self, print_output: bool = True) -> list[str]: """ Read all available output lines produced by device from internal buffer. """ lines: list[str] = [] while not self._device_read_queue.empty(): line = self.readline(0.1, print_output) lines.append(line) return lines def clear_buffer(self) -> None: """ Remove all available output produced by device from internal buffer (queue). """ self.readlines(print_output=False) def write(self, data: bytes) -> None: """Write data bytes to device.""" if not self.is_device_connected(): msg = 'No connection to the device' logger.error(msg) raise TwisterHarnessException(msg) self._write_to_device(data) def initialize_log_files(self, test_name: str = '') -> None: """ Initialize log files (e.g. handler.log) by adding header with information about performed test and current time. """ for log_file_path in self._log_files: with open(log_file_path, 'a+') as log_file: log_file.write(f'\n==== Test {test_name} started at {datetime.now()} ====\n') def _start_reader_thread(self) -> None: self._reader_thread = threading.Thread(target=self._handle_device_output, daemon=True) self._reader_thread.start() def _handle_device_output(self) -> None: """ This method is dedicated to run it in separate thread to read output from device and put them into internal queue and save to log file. """ with open(self.handler_log_path, 'a+') as log_file: while self.is_device_running(): if self.is_device_connected(): output = self._read_device_output().decode(errors='replace').strip() if output: self._device_read_queue.put(output) log_file.write(f'{output}\n') log_file.flush() else: # ignore output from device self._flush_device_output() time.sleep(0.1) def _read_from_queue(self, timeout: float) -> str: """Read data from internal queue""" try: data: str | object = self._device_read_queue.get(timeout=timeout) except queue.Empty as exc: raise TwisterHarnessTimeoutException(f'Read from device timeout occurred ({timeout}s)') from exc return data def _join_reader_thread(self) -> None: if self._reader_thread is not None: self._reader_thread.join(self.base_timeout) self._reader_thread = None def _clear_internal_resources(self) -> None: self._reader_thread = None self._device_read_queue = queue.Queue() self._device_run.clear() self._device_connected.clear() @property def west(self) -> str: """ Return a path to west or if not found - raise an error. Once found west path is stored as internal property to save time of looking for it in the next time. """ if self._west is None: self._west = shutil.which('west') if self._west is None: msg = 'west not found' logger.error(msg) raise TwisterHarnessException(msg) return self._west @abc.abstractmethod def generate_command(self) -> None: """ Generate and set command which will be used during flashing or running device. """ @abc.abstractmethod def _flash_and_run(self) -> None: """Flash and run application on a device.""" @abc.abstractmethod def _connect_device(self) -> None: """Connect with the device (e.g. via serial port).""" @abc.abstractmethod def _disconnect_device(self) -> None: """Disconnect from the device (e.g. from serial port).""" @abc.abstractmethod def _close_device(self) -> None: """Stop application""" @abc.abstractmethod def _read_device_output(self) -> bytes: """ Read device output directly through serial, subprocess, FIFO, etc. Even if device is not connected, this method has to return something (e.g. empty bytes string). This assumption is made to maintain compatibility between various adapters and their reading technique. """ @abc.abstractmethod def _write_to_device(self, data: bytes) -> None: """Write to device directly through serial, subprocess, FIFO, etc.""" @abc.abstractmethod def _flush_device_output(self) -> None: """Flush device connection (serial, subprocess output, FIFO, etc.)""" @abc.abstractmethod def is_device_running(self) -> bool: """Return true if application is running on device.""" @abc.abstractmethod def is_device_connected(self) -> bool: """Return true if device is connected.""" ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/device_adapter.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,357
```python # from __future__ import annotations import io import logging import os import threading import time from pathlib import Path logger = logging.getLogger(__name__) class FifoHandler: """ Class dedicated for handling communication over POSIX system FIFO (named pipes). """ def __init__(self, fifo_path: str | Path, timeout: float): """ :param fifo_path: path to basic fifo name :param timeout: timeout for establishing connection over FIFO """ self._fifo_out_path = str(fifo_path) + '.out' self._fifo_in_path = str(fifo_path) + '.in' self._fifo_out_file: io.FileIO | None = None self._fifo_in_file: io.FileIO | None = None self._open_fifo_thread: threading.Thread | None = None self._opening_monitor_thread: threading.Thread | None = None self._fifo_opened: threading.Event = threading.Event() self._stop_waiting_for_opening: threading.Event = threading.Event() self._timeout = timeout def initiate_connection(self) -> None: """ Opening FIFO could be a blocking operation (it requires also opening FIFO on the other side - by separate program/process). So, to avoid blockage, execute opening FIFO in separate thread and additionally run in second thread opening time monitor to alternatively unblock first thread when timeout will expire. """ self._stop_waiting_for_opening.clear() self._make_fifo_file(self._fifo_out_path) self._make_fifo_file(self._fifo_in_path) if self._open_fifo_thread is None: self._open_fifo_thread = threading.Thread(target=self._open_fifo, daemon=True) self._open_fifo_thread.start() if self._opening_monitor_thread is None: self._opening_monitor_thread = threading.Thread(target=self._opening_monitor, daemon=True) self._opening_monitor_thread.start() @staticmethod def _make_fifo_file(filename: str) -> None: if not os.path.exists(filename): os.mkfifo(filename) def _open_fifo(self) -> None: self._fifo_out_file = open(self._fifo_out_path, 'rb', buffering=0) self._fifo_in_file = open(self._fifo_in_path, 'wb', buffering=0) if not self._stop_waiting_for_opening.is_set(): self._fifo_opened.set() def _opening_monitor(self) -> None: """ Monitor opening FIFO operation - if timeout was expired (or disconnect was called in the meantime), then interrupt opening FIFO in other thread. """ timeout_time: float = time.time() + self._timeout while time.time() < timeout_time and not self._stop_waiting_for_opening.is_set(): if self._fifo_opened.is_set(): return time.sleep(0.1) self._stop_waiting_for_opening.set() self._unblock_open_fifo_operation() def _unblock_open_fifo_operation(self) -> None: """ This is workaround for unblocking opening FIFO operation - imitate opening FIFO "on the other side". """ if os.path.exists(self._fifo_out_path): open(self._fifo_out_path, 'wb', buffering=0) if os.path.exists(self._fifo_in_path): open(self._fifo_in_path, 'rb', buffering=0) def disconnect(self) -> None: self._stop_waiting_for_opening.set() if self._open_fifo_thread and self._open_fifo_thread.is_alive(): self._open_fifo_thread.join(timeout=1) self._open_fifo_thread = None if self._opening_monitor_thread and self._opening_monitor_thread.is_alive(): self._opening_monitor_thread.join(timeout=1) self._opening_monitor_thread = None self._fifo_opened.clear() if self._fifo_out_file: self._fifo_out_file.close() if self._fifo_in_file: self._fifo_in_file.close() if os.path.exists(self._fifo_out_path): os.unlink(self._fifo_out_path) if os.path.exists(self._fifo_in_path): os.unlink(self._fifo_in_path) @property def is_open(self) -> bool: try: return bool( self._fifo_opened.is_set() and self._fifo_in_file is not None and self._fifo_out_file is not None and self._fifo_in_file.fileno() and self._fifo_out_file.fileno() ) except ValueError: return False def read(self, __size: int = -1) -> bytes: return self._fifo_out_file.read(__size) # type: ignore[union-attr] def readline(self, __size: int | None = None) -> bytes: return self._fifo_out_file.readline(__size) # type: ignore[union-attr] def write(self, __buffer: bytes) -> int: return self._fifo_in_file.write(__buffer) # type: ignore[union-attr] def flush_write(self) -> None: if self._fifo_in_file: self._fifo_in_file.flush() def flush_read(self) -> None: if self._fifo_out_file: self._fifo_out_file.flush() ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/device/fifo_handler.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,138
```python # from __future__ import annotations import os import sys import logging from pathlib import Path ZEPHYR_BASE = os.environ['ZEPHYR_BASE'] sys.path.insert(0, os.path.join(ZEPHYR_BASE, 'scripts', 'pylib', 'build_helpers')) from domains import Domains logger = logging.getLogger(__name__) logging.getLogger('pykwalify').setLevel(logging.ERROR) def get_default_domain_name(domains_file: Path | str) -> int: """ Get the default domain name from the domains.yaml file """ domains = Domains.from_file(domains_file) logger.debug("Loaded sysbuild domain data from %s" % domains_file) return domains.get_default_domain().name ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/helpers/domains_helper.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
159
```python # ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/helpers/__init__.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2
```python # from __future__ import annotations import logging import re import time from dataclasses import dataclass, field from inspect import signature from twister_harness.device.device_adapter import DeviceAdapter from twister_harness.exceptions import TwisterHarnessTimeoutException logger = logging.getLogger(__name__) class Shell: """ Helper class that provides methods used to interact with shell application. """ def __init__(self, device: DeviceAdapter, prompt: str = 'uart:~$', timeout: float | None = None) -> None: self._device: DeviceAdapter = device self.prompt: str = prompt self.base_timeout: float = timeout or device.base_timeout def wait_for_prompt(self, timeout: float | None = None) -> bool: """ Send every 0.5 second "enter" command to the device until shell prompt statement will occur (return True) or timeout will be exceeded (return False). """ timeout = timeout or self.base_timeout timeout_time = time.time() + timeout self._device.clear_buffer() while time.time() < timeout_time: self._device.write(b'\n') try: line = self._device.readline(timeout=0.5, print_output=False) except TwisterHarnessTimeoutException: # ignore read timeout and try to send enter once again continue if self.prompt in line: logger.debug('Got prompt') return True return False def exec_command(self, command: str, timeout: float | None = None, print_output: bool = True) -> list[str]: """ Send shell command to a device and return response. Passed command is extended by double enter sings - first one to execute this command on a device, second one to receive next prompt what is a signal that execution was finished. Method returns printout of the executed command. """ timeout = timeout or self.base_timeout command_ext = f'{command}\n\n' regex_prompt = re.escape(self.prompt) regex_command = f'.*{re.escape(command)}' self._device.clear_buffer() self._device.write(command_ext.encode()) lines: list[str] = [] # wait for device command print - it should be done immediately after sending command to device lines.extend(self._device.readlines_until(regex=regex_command, timeout=1.0, print_output=print_output)) # wait for device command execution lines.extend(self._device.readlines_until(regex=regex_prompt, timeout=timeout, print_output=print_output)) return lines def get_filtered_output(self, command_lines: list[str]) -> list[str]: regex_filter = re.compile( '|'.join([ re.escape(self.prompt), '<dbg>', '<inf>', '<wrn>', '<err>' ]) ) return list(filter(lambda l: not regex_filter.search(l), command_lines)) @dataclass class ShellMCUbootArea: name: str version: str image_size: str magic: str = 'unset' swap_type: str = 'none' copy_done: str = 'unset' image_ok: str = 'unset' @classmethod def from_kwargs(cls, **kwargs) -> ShellMCUbootArea: cls_fields = {field for field in signature(cls).parameters} native_args = {} for name, val in kwargs.items(): if name in cls_fields: native_args[name] = val return cls(**native_args) @dataclass class ShellMCUbootCommandParsed: """ Helper class to keep data from `mcuboot` shell command. """ areas: list[ShellMCUbootArea] = field(default_factory=list) @classmethod def create_from_cmd_output(cls, cmd_output: list[str]) -> ShellMCUbootCommandParsed: """ Factory to create class from the output of `mcuboot` shell command. """ areas: list[dict] = [] re_area = re.compile(r'(.+ area.*):\s*$') re_key = re.compile(r'(?P<key>.+):(?P<val>.+)') for line in cmd_output: if m := re_area.search(line): areas.append({'name': m.group(1)}) elif areas: if m := re_key.search(line): areas[-1][m.group('key').strip().replace(' ', '_')] = m.group('val').strip() data_areas: list[ShellMCUbootArea] = [] for area in areas: data_areas.append(ShellMCUbootArea.from_kwargs(**area)) return cls(data_areas) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/helpers/shell.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,007
```python # from __future__ import annotations import logging import re import shlex from subprocess import check_output, getstatusoutput from pathlib import Path from dataclasses import dataclass logger = logging.getLogger(__name__) class MCUmgrException(Exception): """General MCUmgr exception.""" @dataclass class MCUmgrImage: image: int slot: int version: str = '' flags: str = '' hash: str = '' class MCUmgr: """Sample wrapper for mcumgr command-line tool""" mcumgr_exec = 'mcumgr' def __init__(self, connection_options: str): self.conn_opts = connection_options @classmethod def create_for_serial(cls, serial_port: str) -> MCUmgr: return cls(connection_options=f'--conntype serial --connstring={serial_port}') @classmethod def is_available(cls) -> bool: exitcode, output = getstatusoutput(f'{cls.mcumgr_exec} version') if exitcode != 0: logger.warning(f'mcumgr tool not available: {output}') return False return True def run_command(self, cmd: str) -> str: command = f'{self.mcumgr_exec} {self.conn_opts} {cmd}' logger.info(f'CMD: {command}') return check_output(shlex.split(command), text=True) def reset_device(self): self.run_command('reset') def image_upload(self, image: Path | str, slot: int | None = None, timeout: int = 30): command = f'-t {timeout} image upload {image}' if slot is not None: command += f' -e -n {slot}' self.run_command(command) logger.info('Image successfully uploaded') def get_image_list(self) -> list[MCUmgrImage]: output = self.run_command('image list') return self._parse_image_list(output) @staticmethod def _parse_image_list(cmd_output: str) -> list[MCUmgrImage]: image_list = [] re_image = re.compile(r'image=(\d+)\s+slot=(\d+)') re_version = re.compile(r'version:\s+(\S+)') re_flags = re.compile(r'flags:\s+(.+)') re_hash = re.compile(r'hash:\s+(\w+)') for line in cmd_output.splitlines(): if m := re_image.search(line): image_list.append( MCUmgrImage( image=int(m.group(1)), slot=int(m.group(2)) ) ) elif image_list: if m := re_version.search(line): image_list[-1].version = m.group(1) elif m := re_flags.search(line): image_list[-1].flags = m.group(1) elif m := re_hash.search(line): image_list[-1].hash = m.group(1) return image_list def get_hash_to_test(self) -> str: image_list = self.get_image_list() for image in image_list: if 'active' not in image.flags: return image.hash logger.warning(f'Images returned by mcumgr (no not active):\n{image_list}') raise MCUmgrException('No not active image found') def get_hash_to_confirm(self): image_list = self.get_image_list() for image in image_list: if 'confirmed' not in image.flags: return image.hash logger.warning(f'Images returned by mcumgr (no not confirmed):\n{image_list}') raise MCUmgrException('No not confirmed image found') def image_test(self, hash: str | None = None): if not hash: hash = self.get_hash_to_test() self.run_command(f'image test {hash}') def image_confirm(self, hash: str | None = None): if not hash: hash = self.get_hash_to_confirm() self.run_command(f'image confirm {hash}') ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/helpers/mcumgr.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
863
```python # from __future__ import annotations import logging import re from pathlib import Path logger = logging.getLogger(__name__) def find_in_config(config_file: Path | str, config_key: str) -> str: """Find key in config file""" re_key = re.compile(rf'{config_key}=(.+)') with open(config_file) as f: lines = f.readlines() for line in lines: if m := re_key.match(line): logger.debug('Found matching key: %s' % line.strip()) return m.group(1).strip('"\'') logger.debug('Not found key: %s' % config_key) return '' def match_lines(output_lines: list[str], searched_lines: list[str]) -> None: """Check all lines exist in the output""" for sl in searched_lines: assert any(sl in line for line in output_lines) def match_no_lines(output_lines: list[str], searched_lines: list[str]) -> None: """Check lines not found in the output""" for sl in searched_lines: assert all(sl not in line for line in output_lines) ```
/content/code_sandbox/scripts/pylib/pytest-twister-harness/src/twister_harness/helpers/utils.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
240
```python #! /usr/bin/python # # Zephyr's Twister library # # pylint: disable=unused-import # # Set of code that other projects can also import to do things on # Zephyr's sanity check testcases. import logging import yaml try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CLoader as Loader from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import Loader, SafeLoader, Dumper log = logging.getLogger("scl") class EmptyYamlFileException(Exception): pass # # def yaml_load(filename): """ Safely load a YAML document Follows recommendations from path_to_url :param str filename: filename to load :raises yaml.scanner: On YAML scan issues :raises: any other exception on file access errors :return: dictionary representing the YAML document """ try: with open(filename, 'r', encoding='utf-8') as f: return yaml.load(f, Loader=SafeLoader) except yaml.scanner.ScannerError as e: # For errors parsing schema.yaml mark = e.problem_mark cmark = e.context_mark log.error("%s:%d:%d: error: %s (note %s context @%s:%d:%d %s)", mark.name, mark.line, mark.column, e.problem, e.note, cmark.name, cmark.line, cmark.column, e.context) raise # If pykwalify is installed, then the validate function will work -- # otherwise, it is a stub and we'd warn about it. try: import pykwalify.core # Don't print error messages yourself, let us do it logging.getLogger("pykwalify.core").setLevel(50) def _yaml_validate(data, schema): if not schema: return c = pykwalify.core.Core(source_data=data, schema_data=schema) c.validate(raise_exception=True) except ImportError as e: log.warning("can't import pykwalify; won't validate YAML (%s)", e) def _yaml_validate(data, schema): pass def yaml_load_verify(filename, schema): """ Safely load a testcase/sample yaml document and validate it against the YAML schema, returning in case of success the YAML data. :param str filename: name of the file to load and process :param dict schema: loaded YAML schema (can load with :func:`yaml_load`) # 'document.yaml' contains a single YAML document. :raises yaml.scanner.ScannerError: on YAML parsing error :raises pykwalify.errors.SchemaError: on Schema violation error """ # 'document.yaml' contains a single YAML document. y = yaml_load(filename) if not y: raise EmptyYamlFileException('No data in YAML file: %s' % filename) _yaml_validate(y, schema) return y ```
/content/code_sandbox/scripts/pylib/twister/scl.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
674
```python #!/usr/bin/env python3 # # import copy import logging import os import re import sys import threading try: import ply.lex as lex import ply.yacc as yacc except ImportError: sys.exit("PLY library for Python 3 not installed.\n" "Please install the ply package using your workstation's\n" "package manager or the 'pip' tool.") _logger = logging.getLogger('twister') reserved = { 'and' : 'AND', 'or' : 'OR', 'not' : 'NOT', 'in' : 'IN', } tokens = [ "HEX", "STR", "INTEGER", "EQUALS", "NOTEQUALS", "LT", "GT", "LTEQ", "GTEQ", "OPAREN", "CPAREN", "OBRACKET", "CBRACKET", "COMMA", "SYMBOL", "COLON", ] + list(reserved.values()) def t_HEX(t): r"0x[0-9a-fA-F]+" t.value = str(int(t.value, 16)) return t def t_INTEGER(t): r"\d+" t.value = str(int(t.value)) return t def t_STR(t): r'\"([^\\\n]|(\\.))*?\"|\'([^\\\n]|(\\.))*?\'' # nip off the quotation marks t.value = t.value[1:-1] return t t_EQUALS = r"==" t_NOTEQUALS = r"!=" t_LT = r"<" t_GT = r">" t_LTEQ = r"<=" t_GTEQ = r">=" t_OPAREN = r"[(]" t_CPAREN = r"[)]" t_OBRACKET = r"\[" t_CBRACKET = r"\]" t_COMMA = r"," t_COLON = ":" def t_SYMBOL(t): r"[A-Za-z_][0-9A-Za-z_]*" t.type = reserved.get(t.value, "SYMBOL") return t t_ignore = " \t\n" def t_error(t): raise SyntaxError("Unexpected token '%s'" % t.value) lex.lex() precedence = ( ('left', 'OR'), ('left', 'AND'), ('right', 'NOT'), ('nonassoc', 'EQUALS', 'NOTEQUALS', 'GT', 'LT', 'GTEQ', 'LTEQ', 'IN'), ) def p_expr_or(p): 'expr : expr OR expr' p[0] = ("or", p[1], p[3]) def p_expr_and(p): 'expr : expr AND expr' p[0] = ("and", p[1], p[3]) def p_expr_not(p): 'expr : NOT expr' p[0] = ("not", p[2]) def p_expr_parens(p): 'expr : OPAREN expr CPAREN' p[0] = p[2] def p_expr_eval(p): """expr : SYMBOL EQUALS const | SYMBOL NOTEQUALS const | SYMBOL GT number | SYMBOL LT number | SYMBOL GTEQ number | SYMBOL LTEQ number | SYMBOL IN list | SYMBOL COLON STR""" p[0] = (p[2], p[1], p[3]) def p_expr_single(p): """expr : SYMBOL""" p[0] = ("exists", p[1]) def p_func(p): """expr : SYMBOL OPAREN arg_intr CPAREN""" p[0] = [p[1]] p[0].append(p[3]) def p_arg_intr_single(p): """arg_intr : const""" p[0] = [p[1]] def p_arg_intr_mult(p): """arg_intr : arg_intr COMMA const""" p[0] = copy.copy(p[1]) p[0].append(p[3]) def p_list(p): """list : OBRACKET list_intr CBRACKET""" p[0] = p[2] def p_list_intr_single(p): """list_intr : const""" p[0] = [p[1]] def p_list_intr_mult(p): """list_intr : list_intr COMMA const""" p[0] = copy.copy(p[1]) p[0].append(p[3]) def p_const(p): """const : STR | number""" p[0] = p[1] def p_number(p): """number : INTEGER | HEX""" p[0] = p[1] def p_error(p): if p: raise SyntaxError("Unexpected token '%s'" % p.value) else: raise SyntaxError("Unexpected end of expression") if "PARSETAB_DIR" not in os.environ: parser = yacc.yacc(debug=0) else: parser = yacc.yacc(debug=0, outputdir=os.environ["PARSETAB_DIR"]) def ast_sym(ast, env): if ast in env: return str(env[ast]) return "" def ast_sym_int(ast, env): if ast in env: v = env[ast] if v.startswith("0x") or v.startswith("0X"): return int(v, 16) else: return int(v, 10) return 0 def ast_expr(ast, env, edt): if ast[0] == "not": return not ast_expr(ast[1], env, edt) elif ast[0] == "or": return ast_expr(ast[1], env, edt) or ast_expr(ast[2], env, edt) elif ast[0] == "and": return ast_expr(ast[1], env, edt) and ast_expr(ast[2], env, edt) elif ast[0] == "==": return ast_sym(ast[1], env) == ast[2] elif ast[0] == "!=": return ast_sym(ast[1], env) != ast[2] elif ast[0] == ">": return ast_sym_int(ast[1], env) > int(ast[2]) elif ast[0] == "<": return ast_sym_int(ast[1], env) < int(ast[2]) elif ast[0] == ">=": return ast_sym_int(ast[1], env) >= int(ast[2]) elif ast[0] == "<=": return ast_sym_int(ast[1], env) <= int(ast[2]) elif ast[0] == "in": return ast_sym(ast[1], env) in ast[2] elif ast[0] == "exists": return bool(ast_sym(ast[1], env)) elif ast[0] == ":": return bool(re.match(ast[2], ast_sym(ast[1], env))) elif ast[0] == "dt_compat_enabled": compat = ast[1][0] for node in edt.nodes: if compat in node.compats and node.status == "okay": return True return False elif ast[0] == "dt_alias_exists": alias = ast[1][0] for node in edt.nodes: if alias in node.aliases and node.status == "okay": return True return False elif ast[0] == "dt_enabled_alias_with_parent_compat": # Checks if the DT has an enabled alias node whose parent has # a given compatible. For matching things like gpio-leds child # nodes, which do not have compatibles themselves. # # The legacy "dt_compat_enabled_with_alias" form is still # accepted but is now deprecated and causes a warning. This is # meant to give downstream users some time to notice and # adjust. Its argument order only made sense under the (bad) # assumption that the gpio-leds child node has the same compatible alias = ast[1][0] compat = ast[1][1] return ast_handle_dt_enabled_alias_with_parent_compat(edt, alias, compat) elif ast[0] == "dt_compat_enabled_with_alias": compat = ast[1][0] alias = ast[1][1] _logger.warning('dt_compat_enabled_with_alias("%s", "%s"): ' 'this is deprecated, use ' 'dt_enabled_alias_with_parent_compat("%s", "%s") ' 'instead', compat, alias, alias, compat) return ast_handle_dt_enabled_alias_with_parent_compat(edt, alias, compat) elif ast[0] == "dt_label_with_parent_compat_enabled": compat = ast[1][1] label = ast[1][0] node = edt.label2node.get(label) if node is not None: parent = node.parent else: return False return parent is not None and parent.status == 'okay' and parent.matching_compat == compat elif ast[0] == "dt_chosen_enabled": chosen = ast[1][0] node = edt.chosen_node(chosen) if node and node.status == "okay": return True return False elif ast[0] == "dt_nodelabel_enabled": label = ast[1][0] node = edt.label2node.get(label) if node and node.status == "okay": return True return False def ast_handle_dt_enabled_alias_with_parent_compat(edt, alias, compat): # Helper shared with the now deprecated # dt_compat_enabled_with_alias version. for node in edt.nodes: parent = node.parent if parent is None: continue if (node.status == "okay" and alias in node.aliases and parent.matching_compat == compat): return True return False mutex = threading.Lock() def parse(expr_text, env, edt): """Given a text representation of an expression in our language, use the provided environment to determine whether the expression is true or false""" # Like it's C counterpart, state machine is not thread-safe mutex.acquire() try: ast = parser.parse(expr_text) finally: mutex.release() return ast_expr(ast, env, edt) # Just some test code if __name__ == "__main__": local_env = { "A" : "1", "C" : "foo", "D" : "20", "E" : 0x100, "F" : "baz" } for line in open(sys.argv[1]).readlines(): lex.input(line) for tok in iter(lex.token, None): print(tok.type, tok.value) parser = yacc.yacc() print(parser.parse(line)) print(parse(line, local_env, None)) ```
/content/code_sandbox/scripts/pylib/twister/expr_parser.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,372
```python # vim: set syntax=python ts=4 : # class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, str(cfile) + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/error.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
96
```python # vim: set syntax=python ts=4 : # class DisablePyTestCollectionMixin(object): __test__ = False ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/mixins.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
28
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import os from multiprocessing import Lock, Value import re import platform import yaml import scl import logging from pathlib import Path from natsort import natsorted from twisterlib.environment import ZEPHYR_BASE try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class DUT(object): def __init__(self, id=None, serial=None, serial_baud=None, platform=None, product=None, serial_pty=None, connected=False, runner_params=None, pre_script=None, post_script=None, post_flash_script=None, runner=None, flash_timeout=60, flash_with_test=False, flash_before=False): self.serial = serial self.baud = serial_baud or 115200 self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self._failures = Value("i", 0) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.runner_params = runner_params self.flash_before = flash_before self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False self.flash_timeout = flash_timeout self.flash_with_test = flash_with_test @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def counter_increment(self, value=1): with self._counter.get_lock(): self._counter.value += value @property def failures(self): with self._failures.get_lock(): return self._failures.value @failures.setter def failures(self, value): with self._failures.get_lock(): self._failures.value = value def failures_increment(self, value=1): with self._failures.get_lock(): self._failures.value += value def to_dict(self): d = {} exclude = ['_available', '_counter', '_failures', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent', 'Microsoft', 'Nuvoton' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self, env=None): self.detected = [] self.duts = [] self.options = env.options def discover(self): if self.options.generate_hardware_map: self.scan(persistent=self.options.persistent_hardware_map) self.save(self.options.generate_hardware_map) return 0 if not self.options.device_testing and self.options.hardware_map: self.load(self.options.hardware_map) logger.info("Available devices:") self.dump(connected_only=True) return 0 if self.options.device_testing: if self.options.hardware_map: self.load(self.options.hardware_map) if not self.options.platform: self.options.platform = [] for d in self.duts: if d.connected and d.platform != 'unknown': self.options.platform.append(d.platform) elif self.options.device_serial: self.add_device(self.options.device_serial, self.options.platform[0], self.options.pre_script, False, baud=self.options.device_serial_baud, flash_timeout=self.options.device_flash_timeout, flash_with_test=self.options.device_flash_with_test, flash_before=self.options.flash_before, ) elif self.options.device_serial_pty: self.add_device(self.options.device_serial_pty, self.options.platform[0], self.options.pre_script, True, flash_timeout=self.options.device_flash_timeout, flash_with_test=self.options.device_flash_with_test, flash_before=False, ) # the fixtures given by twister command explicitly should be assigned to each DUT if self.options.fixture: for d in self.duts: d.fixtures.extend(self.options.fixture) return 1 def summary(self, selected_platforms): print("\nHardware distribution summary:\n") table = [] header = ['Board', 'ID', 'Counter', 'Failures'] for d in self.duts: if d.connected and d.platform in selected_platforms: row = [d.platform, d.id, d.counter, d.failures] table.append(row) print(tabulate(table, headers=header, tablefmt="github")) def add_device(self, serial, platform, pre_script, is_pty, baud=None, flash_timeout=60, flash_with_test=False, flash_before=False): device = DUT(platform=platform, connected=True, pre_script=pre_script, serial_baud=baud, flash_timeout=flash_timeout, flash_with_test=flash_with_test, flash_before=flash_before ) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') flash_timeout = dut.get('flash_timeout') or self.options.device_flash_timeout flash_with_test = dut.get('flash_with_test') if flash_with_test is None: flash_with_test = self.options.device_flash_with_test flash_before = dut.get('flash_before') if flash_before is None: flash_before = self.options.flash_before and (not (flash_with_test or serial_pty)) platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') runner_params = dut.get('runner_params') serial_pty = dut.get('serial_pty') serial = dut.get('serial') baud = dut.get('baud', None) product = dut.get('product') fixtures = dut.get('fixtures', []) connected= dut.get('connected') and ((serial or serial_pty) is not None) if not connected: continue new_dut = DUT(platform=platform, product=product, runner=runner, runner_params=runner_params, id=id, serial_pty=serial_pty, serial=serial, serial_baud=baud, connected=connected, pre_script=pre_script, flash_before=flash_before, post_script=post_script, post_flash_script=post_flash_script, flash_timeout=flash_timeout, flash_with_test=flash_with_test) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) if by_id.exists(): persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer and d.manufacturer.casefold() in [m.casefold() for m in self.manufacturer]: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue if d.product is None: d.product = 'unknown' s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown', connected=True) for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True s_dev.lock = None self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected = natsorted(self.detected, key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x.get('id', '')) # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if all([ _detected.id == h['id'], _detected.product == h['product'], _detected.match is False, h['connected'] is False ]): h['connected'] = True h['serial'] = _detected.serial _detected.match = True break new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product, 'connected': _connected.connected } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github")) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/hardwaremap.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,076
```python # vim: set syntax=python ts=4 : # import sys import os import logging import pathlib import shutil import subprocess import glob import re import tempfile logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) supported_coverage_formats = { "gcovr": ["html", "xml", "csv", "txt", "coveralls", "sonarqube"], "lcov": ["html", "lcov"] } class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None self.output_formats = None @staticmethod def factory(tool, jobs=None): if tool == 'lcov': t = Lcov(jobs) elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(input_file): logger.debug("Working on %s" % input_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(input_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True capture_complete = False continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True # Keep searching for additional dumps # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue if file_name in extracted_coverage_info: extracted_coverage_info[file_name].append(hex_dump) else: extracted_coverage_info[file_name] = [hex_dump] if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} def merge_hexdumps(self, hexdumps): # Only one hexdump if len(hexdumps) == 1: return hexdumps[0] with tempfile.TemporaryDirectory() as dir: # Write each hexdump to a dedicated temporary folder dirs = [] for idx, dump in enumerate(hexdumps): subdir = dir + f'/{idx}' os.mkdir(subdir) dirs.append(subdir) with open(f'{subdir}/tmp.gcda', 'wb') as fp: fp.write(bytes.fromhex(dump)) # Iteratively call gcov-tool (not gcov) to merge the files merge_tool = self.gcov_tool + '-tool' for d1, d2 in zip(dirs[:-1], dirs[1:]): cmd = [merge_tool, 'merge', d1, d2, '--output', d2] subprocess.call(cmd) # Read back the final output file with open(f'{dirs[-1]}/tmp.gcda', 'rb') as fp: return fp.read(-1).hex() def create_gcda_files(self, extracted_coverage_info): gcda_created = True logger.debug("Generating gcda files") for filename, hexdumps in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue try: hexdump_val = self.merge_hexdumps(hexdumps) with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) except ValueError: logger.exception("Unable to convert hex data for file: {}".format(filename)) gcda_created = False except FileNotFoundError: logger.exception("Unable to create gcda file: {}".format(filename)) gcda_created = False return gcda_created def generate(self, outdir): coverage_completed = True for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: gcda_created = self.create_gcda_files(extracted_coverage_info) if gcda_created: logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data invalid for: {}".format(filename)) coverage_completed = False else: logger.error("Gcov data capture incomplete: {}".format(filename)) coverage_completed = False with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: report_log = { "html": "HTML report generated: {}".format(os.path.join(outdir, "coverage", "index.html")), "lcov": "LCOV report generated: {}".format(os.path.join(outdir, "coverage.info")), "xml": "XML report generated: {}".format(os.path.join(outdir, "coverage", "coverage.xml")), "csv": "CSV report generated: {}".format(os.path.join(outdir, "coverage", "coverage.csv")), "txt": "TXT report generated: {}".format(os.path.join(outdir, "coverage", "coverage.txt")), "coveralls": "Coveralls report generated: {}".format(os.path.join(outdir, "coverage", "coverage.coveralls.json")), "sonarqube": "Sonarqube report generated: {}".format(os.path.join(outdir, "coverage", "coverage.sonarqube.xml")) } for r in self.output_formats.split(','): logger.info(report_log[r]) else: coverage_completed = False logger.debug("All coverage data processed: {}".format(coverage_completed)) return coverage_completed class Lcov(CoverageTool): def __init__(self, jobs=None): super().__init__() self.ignores = [] self.ignore_branch_patterns = [] self.output_formats = "lcov,html" self.version = self.get_version() self.jobs = jobs def get_version(self): try: result = subprocess.run(['lcov', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) version_output = result.stdout.strip().replace('lcov: LCOV version ', '') return version_output except subprocess.CalledProcessError as e: logger.error(f"Unable to determine lcov version: {e}") sys.exit(1) except FileNotFoundError as e: logger.error(f"Unable to find lcov tool: {e}") sys.exit(1) def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def add_ignore_branch_pattern(self, pattern): self.ignore_branch_patterns.append(pattern) @property def is_lcov_v2(self): return self.version.startswith("2") def run_command(self, cmd, coveragelog): if self.is_lcov_v2: # The --ignore-errors source option is added for genhtml as well as # lcov to avoid it exiting due to # samples/application_development/external_lib/ cmd += [ "--ignore-errors", "inconsistent,inconsistent", "--ignore-errors", "negative,negative", "--ignore-errors", "unused,unused", "--ignore-errors", "empty,empty", "--ignore-errors", "mismatch,mismatch", ] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") return subprocess.call(cmd, stdout=coveragelog) def run_lcov(self, args, coveragelog): if self.is_lcov_v2: branch_coverage = "branch_coverage=1" if self.jobs is None: # Default: --parallel=0 will autodetect appropriate parallelism parallel = ["--parallel", "0"] elif self.jobs == 1: # Serial execution requested, don't parallelize at all parallel = [] else: parallel = ["--parallel", str(self.jobs)] else: branch_coverage = "lcov_branch_coverage=1" parallel = [] cmd = [ "lcov", "--gcov-tool", self.gcov_tool, "--rc", branch_coverage, ] + parallel + args return self.run_command(cmd, coveragelog) def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["--capture", "--directory", outdir, "--output-file", coveragefile] self.run_lcov(cmd, coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile] self.run_lcov(cmd, coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: cmd = ["--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile] self.run_lcov(cmd, coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: cmd = ["--remove", coveragefile, i, "--output-file", coveragefile] self.run_lcov(cmd, coveragelog) if 'html' not in self.output_formats.split(','): return 0 cmd = ["genhtml", "--legend", "--branch-coverage", "--prefix", self.base_dir, "-output-directory", os.path.join(outdir, "coverage")] + files return self.run_command(cmd, coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] self.ignore_branch_patterns = [] self.output_formats = "html" self.version = self.get_version() def get_version(self): try: result = subprocess.run(['gcovr', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) version_lines = result.stdout.strip().split('\n') if version_lines: version_output = version_lines[0].replace('gcovr ', '') return version_output except subprocess.CalledProcessError as e: logger.error(f"Unable to determine gcovr version: {e}") sys.exit(1) except FileNotFoundError as e: logger.error(f"Unable to find gcovr tool: {e}") sys.exit(1) def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') def add_ignore_branch_pattern(self, pattern): self.ignore_branch_patterns.append(pattern) @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] @staticmethod def _flatten_list(list): return [a for b in list for a in b] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) if len(self.ignore_branch_patterns) > 0: # Last pattern overrides previous values, so merge all patterns together merged_regex = "|".join([f"({p})" for p in self.ignore_branch_patterns]) excludes += ["--exclude-branches-by-pattern", merged_regex] # Different ifdef-ed implementations of the same function should not be # in conflict treated by GCOVR as separate objects for coverage statistics. mode_options = ["--merge-mode-functions=separate"] # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-ignore-parse-errors=negative_hits.warn_once_per_file", "--gcov-executable", self.gcov_tool, "-e", "tests/*"] cmd += excludes + mode_options + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir] + mode_options, stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) # Convert command line argument (comma-separated list) to gcovr flags report_options = { "html": ["--html", os.path.join(subdir, "index.html"), "--html-details"], "xml": ["--xml", os.path.join(subdir, "coverage.xml"), "--xml-pretty"], "csv": ["--csv", os.path.join(subdir, "coverage.csv")], "txt": ["--txt", os.path.join(subdir, "coverage.txt")], "coveralls": ["--coveralls", os.path.join(subdir, "coverage.coveralls.json"), "--coveralls-pretty"], "sonarqube": ["--sonarqube", os.path.join(subdir, "coverage.sonarqube.xml")] } gcovr_options = self._flatten_list([report_options[r] for r in self.output_formats.split(',')]) return subprocess.call(["gcovr", "-r", self.base_dir] + mode_options + gcovr_options + tracefiles, stdout=coveragelog) def run_coverage(testplan, options): use_system_gcov = False gcov_tool = None for plat in options.coverage_platform: _plat = testplan.get_platform(plat) if _plat and (_plat.type in {"native", "unit"}): use_system_gcov = True if not options.gcov_tool: zephyr_sdk_gcov_tool = os.path.join( os.environ.get("ZEPHYR_SDK_INSTALL_DIR", default=""), "x86_64-zephyr-elf/bin/x86_64-zephyr-elf-gcov") if os.environ.get("ZEPHYR_TOOLCHAIN_VARIANT") == "llvm": llvm_path = os.environ.get("LLVM_TOOLCHAIN_PATH") if llvm_path is not None: llvm_path = os.path.join(llvm_path, "bin") llvm_cov = shutil.which("llvm-cov", path=llvm_path) llvm_cov_ext = pathlib.Path(llvm_cov).suffix gcov_lnk = os.path.join(options.outdir, f"gcov{llvm_cov_ext}") try: os.symlink(llvm_cov, gcov_lnk) except OSError: shutil.copy(llvm_cov, gcov_lnk) gcov_tool = gcov_lnk elif use_system_gcov: gcov_tool = "gcov" elif os.path.exists(zephyr_sdk_gcov_tool): gcov_tool = zephyr_sdk_gcov_tool else: logger.error(f"Can't find a suitable gcov tool. Use --gcov-tool or set ZEPHYR_SDK_INSTALL_DIR.") sys.exit(1) else: gcov_tool = str(options.gcov_tool) logger.info("Generating coverage files...") logger.info(f"Using gcov tool: {gcov_tool}") coverage_tool = CoverageTool.factory(options.coverage_tool, jobs=options.jobs) coverage_tool.gcov_tool = gcov_tool coverage_tool.base_dir = os.path.abspath(options.coverage_basedir) # Apply output format default if options.coverage_formats is not None: coverage_tool.output_formats = options.coverage_formats coverage_tool.add_ignore_file('generated') coverage_tool.add_ignore_directory('tests') coverage_tool.add_ignore_directory('samples') # Ignore branch coverage on LOG_* and LOG_HEXDUMP_* macros # Branch misses are due to the implementation of Z_LOG2 and cannot be avoided coverage_tool.add_ignore_branch_pattern(r"^\s*LOG_(?:HEXDUMP_)?(?:DBG|INF|WRN|ERR)\(.*") # Ignore branch coverage on __ASSERT* macros # Covering the failing case is not desirable as it will immediately terminate the test. coverage_tool.add_ignore_branch_pattern(r"^\s*__ASSERT(?:_EVAL|_NO_MSG|_POST_ACTION)?\(.*") coverage_completed = coverage_tool.generate(options.outdir) return coverage_completed ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/coverage.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,917
```python #!/usr/bin/env python3 # """ Status classes to be used instead of str statuses. """ from enum import Enum class TwisterStatus(str, Enum): def __str__(self): return str(self.value) # All statuses below this comment can be used for TestCase BLOCK = 'blocked' STARTED = 'started' # All statuses below this comment can be used for TestSuite # All statuses below this comment can be used for TestInstance FILTER = 'filtered' # All statuses below this comment can be used for Harness NONE = None ERROR = 'error' FAIL = 'failed' PASS = 'passed' SKIP = 'skipped' ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/statuses.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
150
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : import tarfile import json import os from twisterlib.statuses import TwisterStatus class Artifacts: def __init__(self, env): self.options = env.options def make_tarfile(self, output_filename, source_dirs): root = os.path.basename(self.options.outdir) with tarfile.open(output_filename, "w:bz2") as tar: tar.add(self.options.outdir, recursive=False) for d in source_dirs: f = os.path.relpath(d, self.options.outdir) tar.add(d, arcname=os.path.join(root, f)) def package(self): dirs = [] with open(os.path.join(self.options.outdir, "twister.json"), "r") as json_test_plan: jtp = json.load(json_test_plan) for t in jtp['testsuites']: if t['status'] != TwisterStatus.FILTER: p = t['platform'] normalized = p.replace("/", "_") dirs.append(os.path.join(self.options.outdir, normalized, t['name'])) dirs.extend( [ os.path.join(self.options.outdir, "twister.json"), os.path.join(self.options.outdir, "testplan.json") ] ) self.make_tarfile(self.options.package_artifacts, dirs) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/package.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
298
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import logging import math import os import psutil import re import select import shlex import signal import subprocess import sys import threading import time from pathlib import Path from queue import Queue, Empty from twisterlib.environment import ZEPHYR_BASE, strip_ansi_sequences from twisterlib.error import TwisterException from twisterlib.platform import Platform from twisterlib.statuses import TwisterStatus sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/build_helpers")) from domains import Domains try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: import pty except ImportError as capture_error: if os.name == "nt": # "nt" means that program is running on Windows OS pass # "--device-serial-pty" option is not supported on Windows OS else: raise capture_error logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) SUPPORTED_SIMS = ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp", "xt-sim", "native", "custom"] SUPPORTED_SIMS_IN_PYTEST = ['native', 'qemu'] def terminate_process(proc): """ encapsulate terminate functionality so we do it consistently where ever we might want to terminate the proc. We need try_kill_process_by_pid because of both how newer ninja (1.6.0 or greater) and .NET / renode work. Newer ninja's don't seem to pass SIGTERM down to the children so we need to use try_kill_process_by_pid. """ for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except (ProcessLookupError, psutil.NoSuchProcess): pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.options = None self.run = False self.type_str = type_str self.pid_fn = None self.call_make_run = True self.name = instance.name self.instance = instance self.sourcedir = instance.testsuite.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.generator_cmd = None self.suite_name_check = True self.ready = False self.args = [] self.terminated = False def get_test_timeout(self): return math.ceil(self.instance.testsuite.timeout * self.instance.platform.timeout_multiplier * self.options.timeout_multiplier) def terminate(self, proc): terminate_process(proc) self.terminated = True def _verify_ztest_suite_name(self, harness_status, detected_suite_names, handler_time): """ If test suite names was found in test's C source code, then verify if detected suite names from output correspond to expected suite names (and not in reverse). """ expected_suite_names = self.instance.testsuite.ztest_suite_names logger.debug(f"Expected suite names:{expected_suite_names}") logger.debug(f"Detected suite names:{detected_suite_names}") if not expected_suite_names or \ not harness_status == TwisterStatus.PASS: return if not detected_suite_names: self._missing_suite_name(expected_suite_names, handler_time) return # compare the expect and detect from end one by one without order _d_suite = detected_suite_names[-len(expected_suite_names):] if set(_d_suite) != set(expected_suite_names): if not set(_d_suite).issubset(set(expected_suite_names)): self._missing_suite_name(expected_suite_names, handler_time) def _missing_suite_name(self, expected_suite_names, handler_time): """ Change result of performed test if problem with missing or unpropper suite name was occurred. """ self.instance.status = TwisterStatus.FAIL self.instance.execution_time = handler_time for tc in self.instance.testcases: tc.status = TwisterStatus.FAIL self.instance.reason = f"Testsuite mismatch" logger.debug("Test suite names were not printed or some of them in " \ "output do not correspond with expected: %s", str(expected_suite_names)) def _final_handle_actions(self, harness, handler_time): # only for Ztest tests: harness_class_name = type(harness).__name__ if self.suite_name_check and harness_class_name == "Test": self._verify_ztest_suite_name(harness.status, harness.detected_suite_names, handler_time) if self.instance.status == TwisterStatus.FAIL: return if not harness.matched_run_id and harness.run_id_exists: self.instance.status = TwisterStatus.FAIL self.instance.execution_time = handler_time self.instance.reason = "RunID mismatch" for tc in self.instance.testcases: tc.status = TwisterStatus.FAIL self.instance.record(harness.recording) def get_default_domain_build_dir(self): if self.instance.sysbuild: # Load domain yaml to get default domain build directory # Note: for targets using QEMU, we assume that the target will # have added any additional images to the run target manually domain_path = os.path.join(self.build_dir, "domains.yaml") domains = Domains.from_file(domain_path) logger.debug("Loaded sysbuild domain data from %s" % domain_path) build_dir = domains.get_default_domain().build_dir else: build_dir = self.build_dir return build_dir class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.seed = None self.extra_test_args = None self.line = b"" def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGKILL) except (ProcessLookupError, psutil.NoSuchProcess): pass def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): suffix = '\\r\\n' with open(self.log, "wt") as log_out_fp: timeout_extended = False timeout_time = time.time() + self.get_test_timeout() while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive() and self.line != b"": line_decoded = self.line.decode('utf-8', "replace") if line_decoded.endswith(suffix): stripped_line = line_decoded[:-len(suffix)].rstrip() else: stripped_line = line_decoded.rstrip() logger.debug("OUTPUT: %s", stripped_line) log_out_fp.write(strip_ansi_sequences(line_decoded)) log_out_fp.flush() harness.handle(stripped_line) if harness.status != TwisterStatus.NONE: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) def _create_command(self, robot_test): if robot_test: keywords = os.path.join(self.options.coverage_basedir, 'tests/robot/common.robot') elf = os.path.join(self.build_dir, "zephyr/zephyr.elf") command = [self.generator_cmd] resc = "" uart = "" # os.path.join cannot be used on a Mock object, so we are # explicitly checking the type if isinstance(self.instance.platform, Platform): for board_dir in self.options.board_root: path = os.path.join(Path(board_dir).parent, self.instance.platform.resc) if os.path.exists(path): resc = path break uart = self.instance.platform.uart command = ["renode-test", "--variable", "KEYWORDS:" + keywords, "--variable", "ELF:@" + elf, "--variable", "RESC:@" + resc, "--variable", "UART:" + uart] elif self.call_make_run: command = [self.generator_cmd, "run"] elif self.instance.testsuite.type == "unit": command = [self.binary] else: binary = os.path.join(self.get_default_domain_build_dir(), "zephyr", "zephyr.exe") command = [binary] if self.options.enable_valgrind: command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log", "--track-origins=yes", ] + command # Only valid for native_sim if self.seed is not None: command.append(f"--seed={self.seed}") if self.extra_test_args is not None: command.extend(self.extra_test_args) return command def _create_env(self): env = os.environ.copy() if self.options.enable_asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.options.enable_lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.options.enable_ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") return env def _update_instance_info(self, harness_status, handler_time): self.instance.execution_time = handler_time if not self.terminated and self.returncode != 0: self.instance.status = TwisterStatus.FAIL if self.options.enable_valgrind and self.returncode == 2: self.instance.reason = "Valgrind error" else: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.instance.reason = "Failed" elif harness_status != TwisterStatus.NONE: self.instance.status = harness_status if harness_status == TwisterStatus.FAIL: self.instance.reason = "Failed" else: self.instance.status = TwisterStatus.FAIL self.instance.reason = "Timeout" self.instance.add_missing_case_status(TwisterStatus.BLOCK, "Timeout") def handle(self, harness): robot_test = getattr(harness, "is_robot_test", False) command = self._create_command(robot_test) logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = self._create_env() if robot_test: harness.run_robot_test(command, self) return stderr_log = "{}/handler_stderr.log".format(self.instance.build_dir) with open(stderr_log, "w+") as stderr_log_fp, subprocess.Popen(command, stdout=subprocess.PIPE, stderr=stderr_log_fp, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode if proc.returncode != 0: self.instance.status = TwisterStatus.ERROR self.instance.reason = "BinaryHandler returned {}".format(proc.returncode) self.try_kill_process_by_pid() handler_time = time.time() - start_time # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"], stdin=sys.stdout) self._update_instance_info(harness.status, handler_time) self._final_handle_actions(harness, handler_time) class SimulationHandler(BinaryHandler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) if type_str == 'renode': self.pid_fn = os.path.join(instance.build_dir, "renode.pid") elif type_str == 'native': self.call_make_run = False self.ready = True class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) def get_test_timeout(self): timeout = super().get_test_timeout() if self.options.enable_coverage: # wait more for gcov data to be dumped on console timeout += 120 return timeout def monitor_serial(self, ser, halt_event, harness): log_out_fp = open(self.log, "wb") if self.options.enable_coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True # Wait for serial connection while not ser.isOpen(): time.sleep(0.1) # Clear serial leftover. ser.reset_input_buffer() while ser.isOpen(): if halt_event.is_set(): logger.debug('halted') ser.close() break try: if not ser.in_waiting: # no incoming bytes are waiting to be read from # the serial input buffer, let other threads run time.sleep(0.001) continue # maybe the serial port is still in reset # check status may cause error # wait for more time except OSError: time.sleep(0.001) continue except TypeError: # This exception happens if the serial port was closed and # its file descriptor cleared in between of ser.isOpen() # and ser.in_waiting checks. logger.debug("Serial port is already closed, stop reading.") break serial_line = None try: serial_line = ser.readline() except TypeError: pass # ignore SerialException which may happen during the serial device # power off/on process. except serial.SerialException: pass # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(strip_ansi_sequences(sl).encode('utf-8')) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.status != TwisterStatus.NONE: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testsuite.harness_config.get("fixture") duts_found = [] for d in self.duts: if fixture and fixture not in map(lambda f: f.split(sep=':')[0], d.fixtures): continue if d.platform != device or (d.serial is None and d.serial_pty is None): continue duts_found.append(d) if not duts_found: raise TwisterException(f"No device to serve as {device} platform.") # Select an available DUT with less failures for d in sorted(duts_found, key=lambda _dut: _dut.failures): d.lock.acquire() avail = False if d.available: d.available = 0 d.counter_increment() avail = True logger.debug(f"Retain DUT:{d.platform}, Id:{d.id}, " f"counter:{d.counter}, failures:{d.failures}") d.lock.release() if avail: return d return None def make_dut_available(self, dut): if self.instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: dut.failures_increment() logger.debug(f"Release DUT:{dut.platform}, Id:{dut.id}, " f"counter:{dut.counter}, failures:{dut.failures}") dut.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, stderr = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) if proc.returncode != 0: logger.error(f"Custom script failure: {stderr.decode(errors='ignore')}") except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def _create_command(self, runner, hardware): if (self.options.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.options.west_flash and self.options.west_flash != []: command_extra_args.extend(self.options.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner in ("pyocd", "nrfjprog", "nrfutil"): command_extra_args.append("--dev-id") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % board_id) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % board_id) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % board_id) elif runner == "openocd" and product == "LPC-LINK2 CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("adapter serial %s" % board_id) elif runner == "jlink": command.append("--dev-id") command.append(board_id) elif runner == "linkserver": # for linkserver # --probe=#<number> select by probe index # --probe=<serial number> select by probe serial number command.append("--probe=%s" % board_id) elif runner == "stm32cubeprogrammer": command.append("--tool-opt=sn=%s" % board_id) # Receive parameters from runner_params field. if hardware.runner_params: for param in hardware.runner_params: command.append(param) if command_extra_args: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] return command def _update_instance_info(self, harness_status, handler_time, flash_error): self.instance.execution_time = handler_time if harness_status != TwisterStatus.NONE: self.instance.status = harness_status if harness_status == TwisterStatus.FAIL: self.instance.reason = "Failed" self.instance.add_missing_case_status(TwisterStatus.BLOCK, harness_status) elif not flash_error: self.instance.status = TwisterStatus.FAIL self.instance.reason = "Timeout" if self.instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: self.instance.add_missing_case_status(TwisterStatus.BLOCK, self.instance.reason) def _terminate_pty(self, ser_pty, ser_pty_process): logger.debug(f"Terminating serial-pty:'{ser_pty}'") terminate_process(ser_pty_process) try: (stdout, stderr) = ser_pty_process.communicate(timeout=self.get_test_timeout()) logger.debug(f"Terminated serial-pty:'{ser_pty}', stdout:'{stdout}', stderr:'{stderr}'") except subprocess.TimeoutExpired: logger.debug(f"Terminated serial-pty:'{ser_pty}'") # def _create_serial_connection(self, dut, serial_device, hardware_baud, flash_timeout, serial_pty, ser_pty_process): try: ser = serial.Serial( serial_device, baudrate=hardware_baud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, # the worst case of no serial input timeout=max(flash_timeout, self.get_test_timeout()) ) except serial.SerialException as e: self._handle_serial_exception(e, dut, serial_pty, ser_pty_process) raise return ser def _handle_serial_exception(self, exception, dut, serial_pty, ser_pty_process): self.instance.status = TwisterStatus.FAIL self.instance.reason = "Serial Device Error" logger.error("Serial device error: %s" % (str(exception))) self.instance.add_missing_case_status(TwisterStatus.BLOCK, "Serial Device Error") if serial_pty and ser_pty_process: self._terminate_pty(serial_pty, ser_pty_process) self.make_dut_available(dut) def get_hardware(self): hardware = None try: hardware = self.device_is_available(self.instance) in_waiting = 0 while not hardware: time.sleep(1) in_waiting += 1 if in_waiting%60 == 0: logger.debug(f"Waiting for a DUT to run {self.instance.name}") hardware = self.device_is_available(self.instance) except TwisterException as error: self.instance.status = TwisterStatus.FAIL self.instance.reason = str(error) logger.error(self.instance.reason) return hardware def _get_serial_device(self, serial_pty, hardware_serial): ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen( re.split('[, ]', serial_pty), stdout=master, stdin=master, stderr=master ) except subprocess.CalledProcessError as error: logger.error( "Failed to run subprocess {}, error {}".format( serial_pty, error.output ) ) return serial_device = os.ttyname(slave) else: serial_device = hardware_serial return serial_device, ser_pty_process def handle(self, harness): runner = None hardware = self.get_hardware() if hardware: self.instance.dut = hardware.id else: return runner = hardware.runner or self.options.west_runner serial_pty = hardware.serial_pty serial_device, ser_pty_process = self._get_serial_device(serial_pty, hardware.serial) logger.debug(f"Using serial device {serial_device} @ {hardware.baud} baud") command = self._create_command(runner, hardware) pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) flash_timeout = hardware.flash_timeout if hardware.flash_with_test: flash_timeout += self.get_test_timeout() serial_port = None if hardware.flash_before is False: serial_port = serial_device try: ser = self._create_serial_connection( hardware, serial_port, hardware.baud, flash_timeout, serial_pty, ser_pty_process ) except serial.SerialException: return halt_monitor_evt = threading.Event() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, halt_monitor_evt, harness)) start_time = time.time() t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) flash_error = False try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=flash_timeout) # ignore unencodable unicode chars logger.debug(stdout.decode(errors="ignore")) if proc.returncode != 0: self.instance.status = TwisterStatus.ERROR self.instance.reason = "Device issue (Flash error?)" flash_error = True with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) halt_monitor_evt.set() except subprocess.TimeoutExpired: logger.warning("Flash operation timed out.") self.terminate(proc) (stdout, stderr) = proc.communicate() self.instance.status = TwisterStatus.ERROR self.instance.reason = "Device issue (Timeout)" flash_error = True with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: halt_monitor_evt.set() self.instance.status = TwisterStatus.ERROR self.instance.reason = "Device issue (Flash error)" flash_error = True if post_flash_script: self.run_custom_script(post_flash_script, 30) # Connect to device after flashing it if hardware.flash_before: try: logger.debug(f"Attach serial device {serial_device} @ {hardware.baud} baud") ser.port = serial_device ser.open() except serial.SerialException as e: self._handle_serial_exception(e, hardware, serial_pty, ser_pty_process) return if not flash_error: # Always wait at most the test timeout here after flashing. t.join(self.get_test_timeout()) else: # When the flash error is due exceptions, # twister tell the monitor serial thread # to close the serial. But it is necessary # for this thread being run first and close # have the change to close the serial. t.join(0.1) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) if ser.isOpen(): ser.close() if serial_pty: self._terminate_pty(serial_pty, ser_pty_process) handler_time = time.time() - start_time self._update_instance_info(harness.status, handler_time, flash_error) self._final_handle_actions(harness, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_dut_available(hardware) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") self.stdout_fn = os.path.join(instance.build_dir, "qemu.stdout") self.stderr_fn = os.path.join(instance.build_dir, "qemu.stderr") if instance.testsuite.ignore_qemu_crash: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process execution time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread_get_fifo_names(fifo_fn): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" return fifo_in, fifo_out @staticmethod def _thread_open_files(fifo_in, fifo_out, logfile): # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") return out_fp, in_fp, log_out_fp @staticmethod def _thread_close_files(fifo_in, fifo_out, pid, out_fp, in_fp, log_out_fp): log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except (ProcessLookupError, psutil.NoSuchProcess): # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) @staticmethod def _thread_update_instance_info(handler, handler_time, status, reason): handler.instance.execution_time = handler_time handler.instance.status = status if reason: handler.instance.reason = reason else: handler.instance.reason = "Unknown" @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, harness, ignore_unexpected_eof=False): fifo_in, fifo_out = QEMUHandler._thread_get_fifo_names(fifo_fn) out_fp, in_fp, log_out_fp = QEMUHandler._thread_open_files( fifo_in, fifo_out, logfile ) start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) _status = TwisterStatus.NONE _reason = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if timeout_extended: # Quit early after timeout extension if no more data is being received this_timeout = min(this_timeout, 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: # there's possibility we polled nothing because # of not enough CPU time scheduled by host for # QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and _status == TwisterStatus.NONE: timeout_time = time.time() + (timeout - cpu_time) continue except psutil.NoSuchProcess: pass except ProcessLookupError: _status = TwisterStatus.FAIL _reason = "Execution error" break if _status == TwisterStatus.NONE: _status = TwisterStatus.FAIL _reason = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail _status = TwisterStatus.FAIL _reason = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: _status = TwisterStatus.FAIL _reason = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(strip_ansi_sequences(line)) log_out_fp.flush() line = line.rstrip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.status != TwisterStatus.NONE: # if we have registered a fail make sure the status is not # overridden by a false success message coming from the # testsuite if _status != TwisterStatus.FAIL: _status = harness.status _reason = harness.reason # if we get some status, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete with {_status} ({_reason}) after {handler_time} seconds") QEMUHandler._thread_update_instance_info(handler, handler_time, _status, _reason) QEMUHandler._thread_close_files(fifo_in, fifo_out, pid, out_fp, in_fp, log_out_fp) def _set_qemu_filenames(self, sysbuild_build_dir): # We pass this to QEMU which looks for fifos with .in and .out suffixes. # QEMU fifo will use main build dir self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") # PID file will be created in the main sysbuild app's build dir self.pid_fn = os.path.join(sysbuild_build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log def _create_command(self, sysbuild_build_dir): command = [self.generator_cmd] command += ["-C", sysbuild_build_dir, "run"] return command def _update_instance_info(self, harness_status, is_timeout): if (self.returncode != 0 and not self.ignore_qemu_crash) or \ harness_status == TwisterStatus.NONE: self.instance.status = TwisterStatus.FAIL if is_timeout: self.instance.reason = "Timeout" else: if not self.instance.reason: self.instance.reason = "Exited with {}".format(self.returncode) self.instance.add_missing_case_status(TwisterStatus.BLOCK) def handle(self, harness): self.run = True domain_build_dir = self.get_default_domain_build_dir() command = self._create_command(domain_build_dir) self._set_qemu_filenames(domain_build_dir) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.get_test_timeout(), self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, harness, self.ignore_unexpected_eof)) self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() thread_max_time = time.time() + self.get_test_timeout() if sys.stdout.isatty(): subprocess.call(["stty", "sane"], stdin=sys.stdout) logger.debug("Running %s (%s)" % (self.name, self.type_str)) is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=open(self.stdout_fn, "wt"), stderr=open(self.stderr_fn, "wt"), cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.get_test_timeout()) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True self.terminate(proc) if harness.status == TwisterStatus.PASS: self.returncode = 0 else: self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # messages. self.thread.join(max(thread_max_time - time.time(), 0)) if self.thread.is_alive(): logger.debug("Timed out while monitoring QEMU output") if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") self._update_instance_info(harness.status, is_timeout) self._final_handle_actions(harness, 0) def get_fifo(self): return self.fifo_fn class QEMUWinHandler(Handler): """Spawns a thread to monitor QEMU output from pipes on Windows OS QEMU creates single duplex pipe at //.pipe/path, where path is fifo_fn. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pipe_handle = None self.pid = 0 self.thread = None self.stop_thread = False if instance.testsuite.ignore_qemu_crash: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process execution time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _open_log_file(logfile): return open(logfile, "wt") @staticmethod def _close_log_file(log_file): log_file.close() @staticmethod def _stop_qemu_process(pid): if pid: try: if pid: os.kill(pid, signal.SIGTERM) except (ProcessLookupError, psutil.NoSuchProcess): # Oh well, as long as it's dead! User probably sent Ctrl-C pass except OSError: pass @staticmethod def _monitor_update_instance_info(handler, handler_time, status, reason): handler.instance.execution_time = handler_time handler.instance.status = status if reason: handler.instance.reason = reason else: handler.instance.reason = "Unknown" def _set_qemu_filenames(self, sysbuild_build_dir): # PID file will be created in the main sysbuild app's build dir self.pid_fn = os.path.join(sysbuild_build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log def _create_command(self, sysbuild_build_dir): command = [self.generator_cmd] command += ["-C", sysbuild_build_dir, "run"] return command def _update_instance_info(self, harness_status, is_timeout): if (self.returncode != 0 and not self.ignore_qemu_crash) or \ harness_status == TwisterStatus.NONE: self.instance.status = TwisterStatus.FAIL if is_timeout: self.instance.reason = "Timeout" else: if not self.instance.reason: self.instance.reason = "Exited with {}".format(self.returncode) self.instance.add_missing_case_status(TwisterStatus.BLOCK) def _enqueue_char(self, queue): while not self.stop_thread: if not self.pipe_handle: try: self.pipe_handle = os.open(r"\\.\pipe\\" + self.fifo_fn, os.O_RDONLY) except FileNotFoundError as e: if e.args[0] == 2: # Pipe is not opened yet, try again after a delay. time.sleep(1) continue c = "" try: c = os.read(self.pipe_handle, 1) finally: queue.put(c) def _monitor_output(self, queue, timeout, logfile, pid_fn, harness, ignore_unexpected_eof=False): start_time = time.time() timeout_time = start_time + timeout _status = TwisterStatus.NONE _reason = None line = "" timeout_extended = False self.pid = 0 log_out_fp = self._open_log_file(logfile) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0: try: if self.pid and this_timeout > 0: # there's possibility we polled nothing because # of not enough CPU time scheduled by host for # QEMU process during p.poll(this_timeout) cpu_time = self._get_cpu_time(self.pid) if cpu_time < timeout and _status == TwisterStatus.NONE: timeout_time = time.time() + (timeout - cpu_time) continue except psutil.NoSuchProcess: pass except ProcessLookupError: _status = TwisterStatus.FAIL _reason = "Execution error" break if _status == TwisterStatus.NONE: _status = TwisterStatus.FAIL _reason = "timeout" break if self.pid == 0 and os.path.exists(pid_fn): try: self.pid = int(open(pid_fn).read()) except ValueError: # pid file probably not contains pid yet, continue pass try: c = queue.get_nowait() except Empty: continue try: c = c.decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail _status = TwisterStatus.FAIL _reason = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: _status = TwisterStatus.FAIL _reason = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.rstrip() logger.debug(f"QEMU ({self.pid}): {line}") harness.handle(line) if harness.status != TwisterStatus.NONE: # if we have registered a fail make sure the status is not # overridden by a false success message coming from the # testsuite if _status != TwisterStatus.FAIL: _status = harness.status _reason = harness.reason # if we get some status, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" self.stop_thread = True handler_time = time.time() - start_time logger.debug(f"QEMU ({self.pid}) complete with {_status} ({_reason}) after {handler_time} seconds") self._monitor_update_instance_info(self, handler_time, _status, _reason) self._close_log_file(log_out_fp) self._stop_qemu_process(self.pid) def handle(self, harness): self.run = True domain_build_dir = self.get_default_domain_build_dir() command = self._create_command(domain_build_dir) self._set_qemu_filenames(domain_build_dir) logger.debug("Running %s (%s)" % (self.name, self.type_str)) is_timeout = False self.stop_thread = False queue = Queue() with subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread = threading.Thread(target=self._enqueue_char, args=(queue,)) self.thread.daemon = True self.thread.start() thread_max_time = time.time() + self.get_test_timeout() self._monitor_output(queue, self.get_test_timeout(), self.log_fn, self.pid_fn, harness, self.ignore_unexpected_eof) if (thread_max_time - time.time()) < 0: logger.debug("Timed out while monitoring QEMU output") proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() if harness.status == TwisterStatus.PASS: self.returncode = 0 else: self.returncode = proc.returncode if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({self.pid}): {self.returncode}") os.close(self.pipe_handle) self.pipe_handle = None self._update_instance_info(harness.status, is_timeout) self._final_handle_actions(harness, 0) def get_fifo(self): return self.fifo_fn ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/handlers.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
10,567
```python # vim: set syntax=python ts=4 : # from enum import Enum import os from pathlib import Path import re import logging import contextlib import mmap import glob from typing import List from twisterlib.mixins import DisablePyTestCollectionMixin from twisterlib.environment import canonical_zephyr_base from twisterlib.error import TwisterException, TwisterRuntimeError from twisterlib.statuses import TwisterStatus logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ScanPathResult: """Result of the scan_tesuite_path function call. Attributes: matches A list of test cases warnings A string containing one or more warnings to display has_registered_test_suites Whether or not the path contained any calls to the ztest_register_test_suite macro. has_run_registered_test_suites Whether or not the path contained at least one call to ztest_run_registered_test_suites. has_test_main Whether or not the path contains a definition of test_main(void) ztest_suite_names Names of found ztest suites """ def __init__(self, matches: List[str] = None, warnings: str = None, has_registered_test_suites: bool = False, has_run_registered_test_suites: bool = False, has_test_main: bool = False, ztest_suite_names: List[str] = []): self.matches = matches self.warnings = warnings self.has_registered_test_suites = has_registered_test_suites self.has_run_registered_test_suites = has_run_registered_test_suites self.has_test_main = has_test_main self.ztest_suite_names = ztest_suite_names def __eq__(self, other): if not isinstance(other, ScanPathResult): return False return (sorted(self.matches) == sorted(other.matches) and self.warnings == other.warnings and (self.has_registered_test_suites == other.has_registered_test_suites) and (self.has_run_registered_test_suites == other.has_run_registered_test_suites) and self.has_test_main == other.has_test_main and (sorted(self.ztest_suite_names) == sorted(other.ztest_suite_names))) def scan_file(inf_name): regular_suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) registered_suite_regex = re.compile( br"^\s*ztest_register_test_suite" br"\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) new_suite_regex = re.compile( br"^\s*ZTEST_SUITE\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) testcase_regex = re.compile( br"^\s*(?:ZTEST|ZTEST_F|ZTEST_USER|ZTEST_USER_F)\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*," br"\s*(?P<testcase_name>[a-zA-Z0-9_]+)\s*", re.MULTILINE) # Checks if the file contains a definition of "void test_main(void)" # Since ztest provides a plain test_main implementation it is OK to: # 1. register test suites and not call the run function if and only if # the test doesn't have a custom test_main. # 2. register test suites and a custom test_main definition if and only if # the test also calls ztest_run_registered_test_suites. test_main_regex = re.compile( br"^\s*void\s+test_main\(void\)", re.MULTILINE) registered_suite_run_regex = re.compile( br"^\s*ztest_run_registered_test_suites\(" br"(\*+|&)?(?P<state_identifier>[a-zA-Z0-9_]+)\)", re.MULTILINE) warnings = None has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: regular_suite_regex_matches = \ [m for m in regular_suite_regex.finditer(main_c)] registered_suite_regex_matches = \ [m for m in registered_suite_regex.finditer(main_c)] new_suite_testcase_regex_matches = \ [m for m in testcase_regex.finditer(main_c)] new_suite_regex_matches = \ [m for m in new_suite_regex.finditer(main_c)] if registered_suite_regex_matches: has_registered_test_suites = True if registered_suite_run_regex.search(main_c): has_run_registered_test_suites = True if test_main_regex.search(main_c): has_test_main = True if regular_suite_regex_matches: ztest_suite_names = \ _extract_ztest_suite_names(regular_suite_regex_matches) testcase_names, warnings = \ _find_regular_ztest_testcases(main_c, regular_suite_regex_matches, has_registered_test_suites) elif registered_suite_regex_matches: ztest_suite_names = \ _extract_ztest_suite_names(registered_suite_regex_matches) testcase_names, warnings = \ _find_regular_ztest_testcases(main_c, registered_suite_regex_matches, has_registered_test_suites) elif new_suite_regex_matches or new_suite_testcase_regex_matches: ztest_suite_names = \ _extract_ztest_suite_names(new_suite_regex_matches) testcase_names, warnings = \ _find_new_ztest_testcases(main_c) else: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h ztest_suite_names = [] testcase_names, warnings = None, None return ScanPathResult( matches=testcase_names, warnings=warnings, has_registered_test_suites=has_registered_test_suites, has_run_registered_test_suites=has_run_registered_test_suites, has_test_main=has_test_main, ztest_suite_names=ztest_suite_names) def _extract_ztest_suite_names(suite_regex_matches): ztest_suite_names = \ [m.group("suite_name") for m in suite_regex_matches] ztest_suite_names = \ [name.decode("UTF-8") for name in ztest_suite_names] return ztest_suite_names def _find_regular_ztest_testcases(search_area, suite_regex_matches, is_registered_test_suite): """ Find regular ztest testcases like "ztest_unit_test" or similar. Return testcases' names and eventually found warnings. """ testcase_regex = re.compile( br"""^\s* # empty space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); # ztest_register_test_suite(n, p, ztest_user_unit_test(TESTNAME), (?:ztest_ (?:test_suite\(|register_test_suite\([a-zA-Z0-9_]+\s*,\s*) [a-zA-Z0-9_]+\s*,\s* )? # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)? # Consume the argument that becomes the extra testcase \(\s*(?P<testcase_name>[a-zA-Z0-9_]+) # _setup_teardown() variant has two extra arguments that we ignore (?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)? \s*\)""", # We don't check how it finishes; we don't care re.MULTILINE | re.VERBOSE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) search_start, search_end = \ _get_search_area_boundary(search_area, suite_regex_matches, is_registered_test_suite) limited_search_area = search_area[search_start:search_end] testcase_names, warnings = \ _find_ztest_testcases(limited_search_area, testcase_regex) achtung_matches = re.findall(achtung_regex, limited_search_area) if achtung_matches and warnings is None: achtung = ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) warnings = f"found invalid {achtung} in ztest_test_suite()" return testcase_names, warnings def _get_search_area_boundary(search_area, suite_regex_matches, is_registered_test_suite): """ Get search area boundary based on "ztest_test_suite(...)", "ztest_register_test_suite(...)" or "ztest_run_test_suite(...)" functions occurrence. """ suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) search_start = suite_regex_matches[0].end() suite_run_match = suite_run_regex.search(search_area) if suite_run_match: search_end = suite_run_match.start() elif not suite_run_match and not is_registered_test_suite: raise ValueError("can't find ztest_run_test_suite") else: search_end = re.compile(br"\);", re.MULTILINE) \ .search(search_area, search_start) \ .end() return search_start, search_end def _find_new_ztest_testcases(search_area): """ Find regular ztest testcases like "ZTEST", "ZTEST_F" etc. Return testcases' names and eventually found warnings. """ testcase_regex = re.compile( br"^\s*(?:ZTEST|ZTEST_F|ZTEST_USER|ZTEST_USER_F)\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*," br"\s*(?P<testcase_name>[a-zA-Z0-9_]+)\s*", re.MULTILINE) return _find_ztest_testcases(search_area, testcase_regex) def _find_ztest_testcases(search_area, testcase_regex): """ Parse search area and try to find testcases defined in testcase_regex argument. Return testcase names and eventually found warnings. """ testcase_regex_matches = \ [m for m in testcase_regex.finditer(search_area)] testcase_names = \ [m.group("testcase_name") for m in testcase_regex_matches] testcase_names = [name.decode("UTF-8") for name in testcase_names] warnings = None for testcase_name in testcase_names: if not testcase_name.startswith("test_"): warnings = "Found a test that does not start with test_" testcase_names = \ [tc_name.replace("test_", "", 1) for tc_name in testcase_names] return testcase_names, warnings def find_c_files_in(path: str, extensions: list = ['c', 'cpp', 'cxx', 'cc']) -> list: """ Find C or C++ sources in the directory specified by "path" """ if not os.path.isdir(path): return [] # back up previous CWD oldpwd = os.getcwd() os.chdir(path) filenames = [] for ext in extensions: # glob.glob('**/*.c') does not pick up the base directory filenames += [os.path.join(path, x) for x in glob.glob(f'*.{ext}')] # glob matches in subdirectories too filenames += [os.path.join(path, x) for x in glob.glob(f'**/*.{ext}')] # restore previous CWD os.chdir(oldpwd) return filenames def scan_testsuite_path(testsuite_path): subcases = [] has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False ztest_suite_names = [] src_dir_path = _find_src_dir_path(testsuite_path) for filename in find_c_files_in(src_dir_path): if os.stat(filename).st_size == 0: continue try: result: ScanPathResult = scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) raise TwisterRuntimeError( "%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches if result.has_registered_test_suites: has_registered_test_suites = True if result.has_run_registered_test_suites: has_run_registered_test_suites = True if result.has_test_main: has_test_main = True if result.ztest_suite_names: ztest_suite_names += result.ztest_suite_names except ValueError as e: logger.error("%s: error parsing source file: %s" % (filename, e)) src_dir_pathlib_path = Path(src_dir_path) for filename in find_c_files_in(testsuite_path): # If we have already scanned those files in the src_dir step, skip them. filename_path = Path(filename) if src_dir_pathlib_path in filename_path.parents: continue try: result: ScanPathResult = scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches if result.ztest_suite_names: ztest_suite_names += result.ztest_suite_names except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) if (has_registered_test_suites and has_test_main and not has_run_registered_test_suites): warning = \ "Found call to 'ztest_register_test_suite()' but no "\ "call to 'ztest_run_registered_test_suites()'" logger.error(warning) raise TwisterRuntimeError(warning) return subcases, ztest_suite_names def _find_src_dir_path(test_dir_path): """ Try to find src directory with test source code. Sometimes due to the optimization reasons it is placed in upper directory. """ src_dir_name = "src" src_dir_path = os.path.join(test_dir_path, src_dir_name) if os.path.isdir(src_dir_path): return src_dir_path src_dir_path = os.path.join(test_dir_path, "..", src_dir_name) if os.path.isdir(src_dir_path): return src_dir_path return "" class TestCase(DisablePyTestCollectionMixin): def __init__(self, name=None, testsuite=None): self.duration = 0 self.name = name self._status = TwisterStatus.NONE self.reason = None self.testsuite = testsuite self.output = "" self.freeform = False @property def status(self) -> TwisterStatus: return self._status @status.setter def status(self, value : TwisterStatus) -> None: # Check for illegal assignments by value try: key = value.name if isinstance(value, Enum) else value self._status = TwisterStatus[key] except KeyError: logger.error(f'TestCase assigned status "{value}"' f' without an equivalent in TwisterStatus.' f' Assignment was ignored.') def __lt__(self, other): return self.name < other.name def __repr__(self): return "<TestCase %s with %s>" % (self.name, self.status) def __str__(self): return self.name class TestSuite(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, suite_root, suite_path, name, data=None, detailed_test_id=True): """TestSuite constructor. This gets called by TestPlan as it finds and reads test yaml files. Multiple TestSuite instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testsuite_root os.path.abspath() of one of the --testsuite-root @param suite_path path to testsuite @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ workdir = os.path.relpath(suite_path, suite_root) assert self.check_suite_name(name, suite_root, workdir) self.detailed_test_id = detailed_test_id self.name = self.get_unique(suite_root, workdir, name) if self.detailed_test_id else name self.id = name self.source_dir = suite_path self.source_dir_rel = os.path.relpath(os.path.realpath(suite_path), start=canonical_zephyr_base) self.yamlfile = suite_path self.testcases = [] self.integration_platforms = [] self.ztest_suite_names = [] self._status = TwisterStatus.NONE if data: self.load(data) @property def status(self) -> TwisterStatus: return self._status @status.setter def status(self, value : TwisterStatus) -> None: # Check for illegal assignments by value try: key = value.name if isinstance(value, Enum) else value self._status = TwisterStatus[key] except KeyError: logger.error(f'TestSuite assigned status "{value}"' f' without an equivalent in TwisterStatus.' f' Assignment was ignored.') def load(self, data): for k, v in data.items(): if k != "testcases": setattr(self, k, v) if self.harness == 'console' and not self.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') def add_subcases(self, data, parsed_subcases=None, suite_names=None): testcases = data.get("testcases", []) if testcases: for tc in testcases: self.add_testcase(name=f"{self.id}.{tc}") else: if not parsed_subcases: self.add_testcase(self.id, freeform=True) else: # only add each testcase once for sub in set(parsed_subcases): name = "{}.{}".format(self.id, sub) self.add_testcase(name) if suite_names: self.ztest_suite_names = suite_names def add_testcase(self, name, freeform=False): tc = TestCase(name=name, testsuite=self) tc.freeform = freeform self.testcases.append(tc) @staticmethod def get_unique(testsuite_root, workdir, name): canonical_testsuite_root = os.path.realpath(testsuite_root) if Path(canonical_zephyr_base) in Path(canonical_testsuite_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_ts_root = os.path.relpath(canonical_testsuite_root, start=canonical_zephyr_base) else: relative_ts_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_ts_root, workdir, name)).replace(os.sep, '/') return unique @staticmethod def check_suite_name(name, testsuite_root, workdir): check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testsuite_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return True ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/testsuite.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
4,576
```python from __future__ import annotations import logging import re import yaml from pathlib import Path from dataclasses import dataclass, field try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader logger = logging.getLogger(__name__) class QuarantineException(Exception): pass class Quarantine: """Handle tests under quarantine.""" def __init__(self, quarantine_list=[]) -> None: self.quarantine = QuarantineData() for quarantine_file in quarantine_list: self.quarantine.extend(QuarantineData.load_data_from_yaml(quarantine_file)) def get_matched_quarantine(self, testname, platform, architecture, simulation): qelem = self.quarantine.get_matched_quarantine(testname, platform, architecture, simulation) if qelem: logger.debug('%s quarantined with reason: %s' % (testname, qelem.comment)) return qelem.comment return None @dataclass class QuarantineElement: scenarios: list[str] = field(default_factory=list) platforms: list[str] = field(default_factory=list) architectures: list[str] = field(default_factory=list) simulations: list[str] = field(default_factory=list) comment: str = 'NA' re_scenarios: list = field(default_factory=list) re_platforms: list = field(default_factory=list) re_architectures: list = field(default_factory=list) re_simulations: list = field(default_factory=list) def __post_init__(self): # If there is no entry in filters then take all possible values. # To keep backward compatibility, 'all' keyword might be still used. if 'all' in self.scenarios: self.scenarios = [] if 'all' in self.platforms: self.platforms = [] if 'all' in self.architectures: self.architectures = [] if 'all' in self.simulations: self.simulations = [] # keep precompiled regexp entiries to speed-up matching self.re_scenarios = [re.compile(pat) for pat in self.scenarios] self.re_platforms = [re.compile(pat) for pat in self.platforms] self.re_architectures = [re.compile(pat) for pat in self.architectures] self.re_simulations = [re.compile(pat) for pat in self.simulations] # However, at least one of the filters ('scenarios', platforms' ...) # must be given (there is no sense to put all possible configuration # into quarantine) if not any([self.scenarios, self.platforms, self.architectures, self.simulations]): raise QuarantineException("At least one of filters ('scenarios', 'platforms' ...) " "must be specified") @dataclass class QuarantineData: qlist: list[QuarantineElement] = field(default_factory=list) def __post_init__(self): qelements = [] for qelem in self.qlist: if isinstance(qelem, QuarantineElement): qelements.append(qelem) else: qelements.append(QuarantineElement(**qelem)) self.qlist = qelements @classmethod def load_data_from_yaml(cls, filename: str | Path) -> QuarantineData: """Load quarantine from yaml file.""" with open(filename, 'r', encoding='UTF-8') as yaml_fd: qlist_raw_data: list[dict] = yaml.load(yaml_fd, Loader=SafeLoader) try: if not qlist_raw_data: # in case of loading empty quarantine file return cls() return cls(qlist_raw_data) except Exception as e: logger.error(f'When loading {filename} received error: {e}') raise QuarantineException('Cannot load Quarantine data') from e def extend(self, qdata: QuarantineData) -> None: self.qlist.extend(qdata.qlist) def get_matched_quarantine(self, scenario: str, platform: str, architecture: str, simulation: str) -> QuarantineElement | None: """Return quarantine element if test is matched to quarantine rules""" for qelem in self.qlist: matched: bool = False if (qelem.scenarios and (matched := _is_element_matched(scenario, qelem.re_scenarios)) is False): continue if (qelem.platforms and (matched := _is_element_matched(platform, qelem.re_platforms)) is False): continue if (qelem.architectures and (matched := _is_element_matched(architecture, qelem.re_architectures)) is False): continue if (qelem.simulations and (matched := _is_element_matched(simulation, qelem.re_simulations)) is False): continue if matched: return qelem return None def _is_element_matched(element: str, list_of_elements: list[re.Pattern]) -> bool: """Return True if given element is matching to any of elements from the list""" for pattern in list_of_elements: if pattern.fullmatch(element): return True return False ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/quarantine.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,135
```python # vim: set syntax=python ts=4 : # from __future__ import annotations from enum import Enum import os import hashlib import random import logging import shutil import glob import csv from twisterlib.testsuite import TestCase, TestSuite from twisterlib.platform import Platform from twisterlib.error import BuildError from twisterlib.size_calc import SizeCalculator from twisterlib.statuses import TwisterStatus from twisterlib.handlers import ( Handler, SimulationHandler, BinaryHandler, QEMUHandler, QEMUWinHandler, DeviceHandler, SUPPORTED_SIMS, SUPPORTED_SIMS_IN_PYTEST, ) logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class TestInstance: """Class representing the execution of a particular TestSuite on a platform @param test The TestSuite object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ __test__ = False def __init__(self, testsuite, platform, outdir): self.testsuite: TestSuite = testsuite self.platform: Platform = platform self._status = TwisterStatus.NONE self.reason = "Unknown" self.metrics = dict() self.handler = None self.recording = None self.outdir = outdir self.execution_time = 0 self.build_time = 0 self.retries = 0 self.name = os.path.join(platform.name, testsuite.name) self.dut = None if testsuite.detailed_test_id: self.build_dir = os.path.join(outdir, platform.normalized_name, testsuite.name) else: # if suite is not in zephyr, keep only the part after ".." in reconstructed dir structure source_dir_rel = testsuite.source_dir_rel.rsplit(os.pardir+os.path.sep, 1)[-1] self.build_dir = os.path.join(outdir, platform.normalized_name, source_dir_rel, testsuite.name) self.run_id = self._get_run_id() self.domains = None # Instance need to use sysbuild if a given suite or a platform requires it self.sysbuild = testsuite.sysbuild or platform.sysbuild self.run = False self.testcases: list[TestCase] = [] self.init_cases() self.filters = [] self.filter_type = None def record(self, recording, fname_csv="recording.csv"): if recording: if self.recording is None: self.recording = recording.copy() else: self.recording.extend(recording) filename = os.path.join(self.build_dir, fname_csv) with open(filename, "wt") as csvfile: cw = csv.DictWriter(csvfile, fieldnames = self.recording[0].keys(), lineterminator = os.linesep, quoting = csv.QUOTE_NONNUMERIC) cw.writeheader() cw.writerows(self.recording) @property def status(self) -> TwisterStatus: return self._status @status.setter def status(self, value : TwisterStatus) -> None: # Check for illegal assignments by value try: key = value.name if isinstance(value, Enum) else value self._status = TwisterStatus[key] except KeyError: logger.error(f'TestInstance assigned status "{value}"' f' without an equivalent in TwisterStatus.' f' Assignment was ignored.') def add_filter(self, reason, filter_type): self.filters.append({'type': filter_type, 'reason': reason }) self.status = TwisterStatus.FILTER self.reason = reason self.filter_type = filter_type # Fix an issue with copying objects from testsuite, need better solution. def init_cases(self): for c in self.testsuite.testcases: self.add_testcase(c.name, freeform=c.freeform) def _get_run_id(self): """ generate run id from instance unique identifier and a random number If exist, get cached run id from previous run.""" run_id = "" run_id_file = os.path.join(self.build_dir, "run_id.txt") if os.path.exists(run_id_file): with open(run_id_file, "r") as fp: run_id = fp.read() else: hash_object = hashlib.md5(self.name.encode()) random_str = f"{random.getrandbits(64)}".encode() hash_object.update(random_str) run_id = hash_object.hexdigest() os.makedirs(self.build_dir, exist_ok=True) with open(run_id_file, 'w+') as fp: fp.write(run_id) return run_id def add_missing_case_status(self, status, reason=None): for case in self.testcases: if case.status == TwisterStatus.STARTED: case.status = TwisterStatus.FAIL elif case.status == TwisterStatus.NONE: case.status = status if reason: case.reason = reason else: case.reason = self.reason def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name def set_case_status_by_name(self, name, status, reason=None): tc = self.get_case_or_create(name) tc.status = status if reason: tc.reason = reason return tc def add_testcase(self, name, freeform=False): tc = TestCase(name=name) tc.freeform = freeform self.testcases.append(tc) return tc def get_case_by_name(self, name): for c in self.testcases: if c.name == name: return c return None def get_case_or_create(self, name): for c in self.testcases: if c.name == name: return c logger.debug(f"Could not find a matching testcase for {name}") tc = TestCase(name=name) self.testcases.append(tc) return tc @staticmethod def testsuite_runnable(testsuite, fixtures): can_run = False # console harness allows us to run the test and capture data. if testsuite.harness in [ 'console', 'ztest', 'pytest', 'test', 'gtest', 'robot']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testsuite.harness_config.get('fixture') if fixture: can_run = fixture in map(lambda f: f.split(sep=':')[0], fixtures) return can_run def setup_handler(self, env): if self.handler: return options = env.options handler = Handler(self, "") if options.device_testing: handler = DeviceHandler(self, "device") handler.call_make_run = False handler.ready = True elif self.platform.simulation != "na": if self.platform.simulation == "qemu": if os.name != "nt": handler = QEMUHandler(self, "qemu") else: handler = QEMUWinHandler(self, "qemu") handler.args.append(f"QEMU_PIPE={handler.get_fifo()}") handler.ready = True else: handler = SimulationHandler(self, self.platform.simulation) if self.platform.simulation_exec and shutil.which(self.platform.simulation_exec): handler.ready = True elif self.testsuite.type == "unit": handler = BinaryHandler(self, "unit") handler.binary = os.path.join(self.build_dir, "testbinary") if options.enable_coverage: handler.args.append("COVERAGE=1") handler.call_make_run = False handler.ready = True if handler: handler.options = options handler.generator_cmd = env.generator_cmd handler.suite_name_check = not options.disable_suite_name_check self.handler = handler # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[], hardware_map=None): if os.name == 'nt': # running on simulators is currently supported only for QEMU on Windows if self.platform.simulation not in ('na', 'qemu'): return False # check presence of QEMU on Windows if self.platform.simulation == 'qemu' and 'QEMU_BIN_PATH' not in os.environ: return False # we asked for build-only on the command line if self.testsuite.build_only: return False # Do not run slow tests: skip_slow = self.testsuite.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testsuite.type == "unit" or \ self.platform.type == "native" or \ (self.platform.simulation in SUPPORTED_SIMS and \ self.platform.simulation not in self.testsuite.simulation_exclude) or \ filter == 'runnable') # check if test is runnable in pytest if self.testsuite.harness == 'pytest': target_ready = bool(filter == 'runnable' or self.platform.simulation in SUPPORTED_SIMS_IN_PYTEST) SUPPORTED_SIMS_WITH_EXEC = ['nsim', 'mdb-nsim', 'renode', 'tsim', 'native'] if filter != 'runnable' and \ self.platform.simulation in SUPPORTED_SIMS_WITH_EXEC and \ self.platform.simulation_exec: if not shutil.which(self.platform.simulation_exec): target_ready = False testsuite_runnable = self.testsuite_runnable(self.testsuite, fixtures) if hardware_map: for h in hardware_map.duts: if (h.platform == self.platform.name and self.testsuite_runnable(self.testsuite, h.fixtures)): testsuite_runnable = True break return testsuite_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testsuite.extra_configs: new_config_list = [] # some configs might be conditional on arch or platform, see if we # have a namespace defined and apply only if the namespace matches. # we currently support both arch: and platform: for config in self.testsuite.extra_configs: cond_config = config.split(":") if cond_config[0] == "arch" and len(cond_config) == 3: if self.platform.arch == cond_config[1]: new_config_list.append(cond_config[2]) elif cond_config[0] == "platform" and len(cond_config) == 3: if self.platform.name == cond_config[1]: new_config_list.append(cond_config[2]) else: new_config_list.append(config) content = "\n".join(new_config_list) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testsuite_extra.conf") with open(file, "w", encoding='utf-8') as f: f.write(content) return content def calculate_sizes(self, from_buildlog: bool = False, generate_warning: bool = True) -> SizeCalculator: """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ elf_filepath = self.get_elf_file() buildlog_filepath = self.get_buildlog_file() if from_buildlog else '' return SizeCalculator(elf_filename=elf_filepath, extra_sections=self.testsuite.extra_sections, buildlog_filepath=buildlog_filepath, generate_warning=generate_warning) def get_elf_file(self) -> str: if self.sysbuild: build_dir = self.domains.get_default_domain().build_dir else: build_dir = self.build_dir fns = glob.glob(os.path.join(build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(build_dir, "testbinary"))) blocklist = [ 'remapped', # used for xtensa plaforms 'zefi', # EFI for Zephyr 'qemu', # elf files generated after running in qemu '_pre'] fns = [x for x in fns if not any(bad in os.path.basename(x) for bad in blocklist)] if not fns: raise BuildError("Missing output binary") elif len(fns) > 1: logger.warning(f"multiple ELF files detected: {', '.join(fns)}") return fns[0] def get_buildlog_file(self) -> str: """Get path to build.log file. @raises BuildError: Incorrect amount (!=1) of build logs. @return: Path to build.log (str). """ buildlog_paths = glob.glob(os.path.join(self.build_dir, "build.log")) if len(buildlog_paths) != 1: raise BuildError("Missing/multiple build.log file.") return buildlog_paths[0] def __repr__(self): return "<TestSuite %s on %s>" % (self.testsuite.name, self.platform.name) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/testinstance.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,108
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import os import sys import re import subprocess import glob import json import collections from collections import OrderedDict from itertools import islice import logging import copy import shutil import random import snippets from pathlib import Path from argparse import Namespace logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) try: from anytree import RenderTree, Node, find except ImportError: print("Install the anytree module to use the --test-tree option") from twisterlib.testsuite import TestSuite, scan_testsuite_path from twisterlib.error import TwisterRuntimeError from twisterlib.platform import Platform from twisterlib.config_parser import TwisterConfigParser from twisterlib.statuses import TwisterStatus from twisterlib.testinstance import TestInstance from twisterlib.quarantine import Quarantine import list_boards from zephyr_module import parse_modules ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl class Filters: # platform keys PLATFORM_KEY = 'platform key filter' # filters provided on command line by the user/tester CMD_LINE = 'command line filter' # filters in the testsuite yaml definition TESTSUITE = 'testsuite filter' # filters in the testplan yaml definition TESTPLAN = 'testplan filter' # filters related to platform definition PLATFORM = 'Platform related filter' # in case a test suite was quarantined. QUARANTINE = 'Quarantine filter' # in case a test suite is skipped intentionally . SKIP = 'Skip filter' # in case of incompatibility between selected and allowed toolchains. TOOLCHAIN = 'Toolchain filter' # in case an optional module is not available MODULE = 'Module filter' class TestLevel: name = None levels = [] scenarios = [] class TestPlan: __test__ = False # for pytest to skip this class when collects tests config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') suite_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testsuite-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) tc_schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "test-config-schema.yaml") SAMPLE_FILENAME = 'sample.yaml' TESTSUITE_FILENAME = 'testcase.yaml' def __init__(self, env=None): self.options = env.options self.env = env # Keep track of which test cases we've filtered out and why self.testsuites = {} self.quarantine = None self.platforms = [] self.platform_names = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.load_errors = 0 self.instances = dict() self.instance_fail_count = 0 self.warnings = 0 self.scenarios = [] self.hwm = env.hwm # used during creating shorter build paths self.link_dir_counter = 0 self.modules = [] self.run_individual_testsuite = [] self.levels = [] self.test_config = {} def get_level(self, name): level = next((l for l in self.levels if l.name == name), None) return level def parse_configuration(self, config_file): if os.path.exists(config_file): tc_schema = scl.yaml_load(self.tc_schema_path) self.test_config = scl.yaml_load_verify(config_file, tc_schema) else: raise TwisterRuntimeError(f"File {config_file} not found.") levels = self.test_config.get('levels', []) # Do first pass on levels to get initial data. for level in levels: adds = [] for s in level.get('adds', []): r = re.compile(s) adds.extend(list(filter(r.fullmatch, self.scenarios))) tl = TestLevel() tl.name = level['name'] tl.scenarios = adds tl.levels = level.get('inherits', []) self.levels.append(tl) # Go over levels again to resolve inheritance. for level in levels: inherit = level.get('inherits', []) _level = self.get_level(level['name']) if inherit: for inherted_level in inherit: _inherited = self.get_level(inherted_level) _inherited_scenarios = _inherited.scenarios level_scenarios = _level.scenarios level_scenarios.extend(_inherited_scenarios) def find_subtests(self): sub_tests = self.options.sub_test if sub_tests: for subtest in sub_tests: _subtests = self.get_testsuite(subtest) for _subtest in _subtests: self.run_individual_testsuite.append(_subtest.name) if self.run_individual_testsuite: logger.info("Running the following tests:") for test in self.run_individual_testsuite: print(" - {}".format(test)) else: raise TwisterRuntimeError("Tests not found") def discover(self): self.handle_modules() if self.options.test: self.run_individual_testsuite = self.options.test num = self.add_testsuites(testsuite_filter=self.run_individual_testsuite) if num == 0: raise TwisterRuntimeError("No test cases found at the specified location...") self.find_subtests() # get list of scenarios we have parsed into one list for _, ts in self.testsuites.items(): self.scenarios.append(ts.id) self.report_duplicates() self.parse_configuration(config_file=self.env.test_config) self.add_configurations() if self.load_errors: raise TwisterRuntimeError("Errors while loading configurations") # handle quarantine ql = self.options.quarantine_list qv = self.options.quarantine_verify if qv and not ql: logger.error("No quarantine list given to be verified") raise TwisterRuntimeError("No quarantine list given to be verified") if ql: for quarantine_file in ql: try: # validate quarantine yaml file against the provided schema scl.yaml_load_verify(quarantine_file, self.quarantine_schema) except scl.EmptyYamlFileException: logger.debug(f'Quarantine file {quarantine_file} is empty') self.quarantine = Quarantine(ql) def load(self): if self.options.report_suffix: last_run = os.path.join(self.options.outdir, "twister_{}.json".format(self.options.report_suffix)) else: last_run = os.path.join(self.options.outdir, "twister.json") if self.options.only_failed or self.options.report_summary is not None: self.load_from_file(last_run) self.selected_platforms = set(p.platform.name for p in self.instances.values()) elif self.options.load_tests: self.load_from_file(self.options.load_tests) self.selected_platforms = set(p.platform.name for p in self.instances.values()) elif self.options.test_only: # Get list of connected hardware and filter tests to only be run on connected hardware. # If the platform does not exist in the hardware map or was not specified by --platform, # just skip it. connected_list = self.options.platform if self.options.exclude_platform: for excluded in self.options.exclude_platform: if excluded in connected_list: connected_list.remove(excluded) self.load_from_file(last_run, filter_platform=connected_list) self.selected_platforms = set(p.platform.name for p in self.instances.values()) else: self.apply_filters() if self.options.subset: s = self.options.subset try: subset, sets = (int(x) for x in s.split("/")) except ValueError: raise TwisterRuntimeError("Bad subset value.") if subset > sets: raise TwisterRuntimeError("subset should not exceed the total number of sets") if int(subset) > 0 and int(sets) >= int(subset): logger.info("Running only a subset: %s/%s" % (subset, sets)) else: raise TwisterRuntimeError(f"You have provided a wrong subset value: {self.options.subset}.") self.generate_subset(subset, int(sets)) def generate_subset(self, subset, sets): # Test instances are sorted depending on the context. For CI runs # the execution order is: "plat1-testA, plat1-testB, ..., # plat1-testZ, plat2-testA, ...". For hardware tests # (device_testing), were multiple physical platforms can run the tests # in parallel, it is more efficient to run in the order: # "plat1-testA, plat2-testA, ..., plat1-testB, plat2-testB, ..." if self.options.device_testing: self.instances = OrderedDict(sorted(self.instances.items(), key=lambda x: x[0][x[0].find("/") + 1:])) else: self.instances = OrderedDict(sorted(self.instances.items())) if self.options.shuffle_tests: seed_value = int.from_bytes(os.urandom(8), byteorder="big") if self.options.shuffle_tests_seed is not None: seed_value = self.options.shuffle_tests_seed logger.info(f"Shuffle tests with seed: {seed_value}") random.seed(seed_value) temp_list = list(self.instances.items()) random.shuffle(temp_list) self.instances = OrderedDict(temp_list) # Do calculation based on what is actually going to be run and evaluated # at runtime, ignore the cases we already know going to be skipped. # This fixes an issue where some sets would get majority of skips and # basically run nothing beside filtering. to_run = {k : v for k,v in self.instances.items() if v.status == TwisterStatus.NONE} total = len(to_run) per_set = int(total / sets) num_extra_sets = total - (per_set * sets) # Try and be more fair for rounding error with integer division # so the last subset doesn't get overloaded, we add 1 extra to # subsets 1..num_extra_sets. if subset <= num_extra_sets: start = (subset - 1) * (per_set + 1) end = start + per_set + 1 else: base = num_extra_sets * (per_set + 1) start = ((subset - num_extra_sets - 1) * per_set) + base end = start + per_set sliced_instances = islice(to_run.items(), start, end) skipped = {k : v for k,v in self.instances.items() if v.status == TwisterStatus.SKIP} errors = {k : v for k,v in self.instances.items() if v.status == TwisterStatus.ERROR} self.instances = OrderedDict(sliced_instances) if subset == 1: # add all pre-filtered tests that are skipped or got error status # to the first set to allow for better distribution among all sets. self.instances.update(skipped) self.instances.update(errors) def handle_modules(self): # get all enabled west projects modules_meta = parse_modules(ZEPHYR_BASE) self.modules = [module.meta.get('name') for module in modules_meta] def report(self): if self.options.test_tree: self.report_test_tree() return 0 elif self.options.list_tests: self.report_test_list() return 0 elif self.options.list_tags: self.report_tag_list() return 0 return 1 def report_duplicates(self): dupes = [item for item, count in collections.Counter(self.scenarios).items() if count > 1] if dupes: msg = "Duplicated test scenarios found:\n" for dupe in dupes: msg += ("- {} found in:\n".format(dupe)) for dc in self.get_testsuite(dupe): msg += (" - {}\n".format(dc.yamlfile)) raise TwisterRuntimeError(msg) else: logger.debug("No duplicates found.") def report_tag_list(self): tags = set() for _, tc in self.testsuites.items(): tags = tags.union(tc.tags) for t in tags: print("- {}".format(t)) def report_test_tree(self): tests_list = self.get_tests_list() testsuite = Node("Testsuite") samples = Node("Samples", parent=testsuite) tests = Node("Tests", parent=testsuite) for test in sorted(tests_list): if test.startswith("sample."): sec = test.split(".") area = find(samples, lambda node: node.name == sec[1] and node.parent == samples) if not area: area = Node(sec[1], parent=samples) Node(test, parent=area) else: sec = test.split(".") area = find(tests, lambda node: node.name == sec[0] and node.parent == tests) if not area: area = Node(sec[0], parent=tests) if area and len(sec) > 2: subarea = find(area, lambda node: node.name == sec[1] and node.parent == area) if not subarea: subarea = Node(sec[1], parent=area) Node(test, parent=subarea) for pre, _, node in RenderTree(testsuite): print("%s%s" % (pre, node.name)) def report_test_list(self): tests_list = self.get_tests_list() cnt = 0 for test in sorted(tests_list): cnt = cnt + 1 print(" - {}".format(test)) print("{} total.".format(cnt)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def add_configurations(self): board_dirs = set() # Create a list of board roots as defined by the build system in general # Note, internally in twister a board root includes the `boards` folder # but in Zephyr build system, the board root is without the `boards` in folder path. board_roots = [Path(os.path.dirname(root)) for root in self.env.board_roots] lb_args = Namespace(arch_roots=[Path(ZEPHYR_BASE)], soc_roots=[Path(ZEPHYR_BASE), Path(ZEPHYR_BASE) / 'subsys' / 'testsuite'], board_roots=board_roots, board=None, board_dir=None) v1_boards = list_boards.find_boards(lb_args) v2_dirs = list_boards.find_v2_board_dirs(lb_args) for b in v1_boards: board_dirs.add(b.dir) board_dirs.update(v2_dirs) logger.debug("Reading platform configuration files under %s..." % self.env.board_roots) platform_config = self.test_config.get('platforms', {}) for folder in board_dirs: for file in glob.glob(os.path.join(folder, "*.yaml")): # If the user set a platform filter, we can, if no other option would increase # the allowed platform pool, save on time by not loading YAMLs of any boards # that do not start with the required names. if self.options.platform and \ not self.options.all and \ not self.options.integration and \ not any([ os.path.basename(file).startswith( re.split('[/@]', p)[0] ) for p in self.options.platform ]): continue try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if not platform.twister: continue self.platforms.append(platform) if not platform_config.get('override_default_platforms', False): if platform.default: self.default_platforms.append(platform.name) else: if platform.name in platform_config.get('default_platforms', []): logger.debug(f"adding {platform.name} to default platforms") self.default_platforms.append(platform.name) # support board@revision # if there is already an existed <board>_<revision>.yaml, then use it to # load platform directly, otherwise, iterate the directory to # get all valid board revision based on each <board>_<revision>.conf. if '@' not in platform.name: tmp_dir = os.listdir(os.path.dirname(file)) for item in tmp_dir: # Need to make sure the revision matches # the permitted patterns as described in # cmake/modules/extensions.cmake. revision_patterns = ["[A-Z]", "[0-9]+", "(0|[1-9][0-9]*)(_[0-9]+){0,2}"] for pattern in revision_patterns: result = re.match(f"{platform.name}_(?P<revision>{pattern})\\.conf", item) if result: revision = result.group("revision") yaml_file = f"{platform.name}_{revision}.yaml" if yaml_file not in tmp_dir: platform_revision = copy.deepcopy(platform) revision = revision.replace("_", ".") platform_revision.name = f"{platform.name}@{revision}" platform_revision.normalized_name = platform_revision.name.replace("/", "_") platform_revision.default = False self.platforms.append(platform_revision) break except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 self.platform_names = [p.name for p in self.platforms] def get_all_tests(self): testcases = [] for _, ts in self.testsuites.items(): for case in ts.testcases: testcases.append(case.name) return testcases def get_tests_list(self): testcases = [] if tag_filter := self.options.tag: for _, ts in self.testsuites.items(): if ts.tags.intersection(tag_filter): for case in ts.testcases: testcases.append(case.name) else: for _, ts in self.testsuites.items(): for case in ts.testcases: testcases.append(case.name) if exclude_tag := self.options.exclude_tag: for _, ts in self.testsuites.items(): if ts.tags.intersection(exclude_tag): for case in ts.testcases: if case.name in testcases: testcases.remove(case.name) return testcases def add_testsuites(self, testsuite_filter=[]): for root in self.env.test_roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTSUITE_FILENAME in filenames: filename = self.TESTSUITE_FILENAME else: continue logger.debug("Found possible testsuite in " + dirpath) suite_yaml_path = os.path.join(dirpath, filename) suite_path = os.path.dirname(suite_yaml_path) for alt_config_root in self.env.alt_config_root: alt_config = os.path.join(os.path.abspath(alt_config_root), os.path.relpath(suite_path, root), filename) if os.path.exists(alt_config): logger.info("Using alternative configuration from %s" % os.path.normpath(alt_config)) suite_yaml_path = alt_config break try: parsed_data = TwisterConfigParser(suite_yaml_path, self.suite_schema) parsed_data.load() subcases = None ztest_suite_names = None for name in parsed_data.scenarios.keys(): suite_dict = parsed_data.get_scenario(name) suite = TestSuite(root, suite_path, name, data=suite_dict, detailed_test_id=self.options.detailed_test_id) if suite.harness in ['ztest', 'test']: if subcases is None: # scan it only once per testsuite subcases, ztest_suite_names = scan_testsuite_path(suite_path) suite.add_subcases(suite_dict, subcases, ztest_suite_names) else: suite.add_subcases(suite_dict) if testsuite_filter: scenario = os.path.basename(suite.name) if suite.name and (suite.name in testsuite_filter or scenario in testsuite_filter): self.testsuites[suite.name] = suite else: self.testsuites[suite.name] = suite except Exception as e: logger.error(f"{suite_path}: can't load (skipping): {e!r}") self.load_errors += 1 return len(self.testsuites) def __str__(self): return self.name def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def handle_quarantined_tests(self, instance: TestInstance, plat: Platform): if self.quarantine: matched_quarantine = self.quarantine.get_matched_quarantine( instance.testsuite.id, plat.name, plat.arch, plat.simulation ) if matched_quarantine and not self.options.quarantine_verify: instance.add_filter("Quarantine: " + matched_quarantine, Filters.QUARANTINE) return if not matched_quarantine and self.options.quarantine_verify: instance.add_filter("Not under quarantine", Filters.QUARANTINE) def load_from_file(self, file, filter_platform=[]): try: with open(file, "r") as json_test_plan: jtp = json.load(json_test_plan) instance_list = [] for ts in jtp.get("testsuites", []): logger.debug(f"loading {ts['name']}...") testsuite = ts["name"] platform = self.get_platform(ts["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testsuites[testsuite], platform, self.env.outdir) if ts.get("run_id"): instance.run_id = ts.get("run_id") if self.options.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.options.enable_slow, tfilter, self.options.fixture, self.hwm ) instance.metrics['handler_time'] = ts.get('execution_time', 0) instance.metrics['used_ram'] = ts.get("used_ram", 0) instance.metrics['used_rom'] = ts.get("used_rom",0) instance.metrics['available_ram'] = ts.get('available_ram', 0) instance.metrics['available_rom'] = ts.get('available_rom', 0) status = ts.get('status') status = TwisterStatus(status) if status else TwisterStatus.NONE reason = ts.get("reason", "Unknown") if status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: if self.options.report_summary is not None: instance.status = status instance.reason = reason self.instance_fail_count += 1 else: instance.status = TwisterStatus.NONE instance.reason = None instance.retries += 1 # test marked as passed (built only) but can run when # --test-only is used. Reset status to capture new results. elif status == TwisterStatus.PASS and instance.run and self.options.test_only: instance.status = TwisterStatus.NONE instance.reason = None else: instance.status = status instance.reason = reason self.handle_quarantined_tests(instance, platform) for tc in ts.get('testcases', []): identifier = tc['identifier'] tc_status = tc.get('status') tc_status = TwisterStatus(tc_status) if tc_status else TwisterStatus.NONE tc_reason = None # we set reason only if status is valid, it might have been # reset above... if instance.status != TwisterStatus.NONE: tc_reason = tc.get('reason') if tc_status != TwisterStatus.NONE: case = instance.set_case_status_by_name(identifier, tc_status, tc_reason) case.duration = tc.get('execution_time', 0) if tc.get('log'): case.output = tc.get('log') instance.create_overlay(platform, self.options.enable_asan, self.options.enable_ubsan, self.options.enable_coverage, self.options.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except FileNotFoundError as e: logger.error(f"{e}") return 1 def apply_filters(self, **kwargs): toolchain = self.env.toolchain platform_filter = self.options.platform vendor_filter = self.options.vendor exclude_platform = self.options.exclude_platform testsuite_filter = self.run_individual_testsuite arch_filter = self.options.arch tag_filter = self.options.tag exclude_tag = self.options.exclude_tag all_filter = self.options.all runnable = (self.options.device_testing or self.options.filter == 'runnable') force_toolchain = self.options.force_toolchain force_platform = self.options.force_platform slow_only = self.options.enable_slow_only ignore_platform_key = self.options.ignore_platform_key emu_filter = self.options.emulation_only logger.debug("platform filter: " + str(platform_filter)) logger.debug(" vendor filter: " + str(vendor_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False vendor_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter and not vendor_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True elif vendor_filter: vendor_platforms = True if platform_filter: self.verify_platforms_existence(platform_filter, f"platform_filter") platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif vendor_filter: platforms = list(filter(lambda p: p.vendor in vendor_filter, self.platforms)) logger.info(f"Selecting platforms by vendors: {','.join(vendor_filter)}") elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: _platforms = list(filter(lambda p: p.name in self.default_platforms, self.platforms)) platforms = [] # default platforms that can't be run are dropped from the list of # the default platforms list. Default platforms should always be # runnable. for p in _platforms: if p.simulation and p.simulation_exec: if shutil.which(p.simulation_exec): platforms.append(p) else: platforms.append(p) else: platforms = self.platforms platform_config = self.test_config.get('platforms', {}) logger.info("Building initial testsuite list...") keyed_tests = {} for ts_name, ts in self.testsuites.items(): if ts.build_on_all and not platform_filter and platform_config.get('increased_platform_scope', True): platform_scope = self.platforms elif ts.integration_platforms: integration_platforms = list(filter(lambda item: item.name in ts.integration_platforms, self.platforms)) if self.options.integration: self.verify_platforms_existence( ts.integration_platforms, f"{ts_name} - integration_platforms") platform_scope = integration_platforms else: # if not in integration mode, still add integration platforms to the list if not platform_filter: self.verify_platforms_existence( ts.integration_platforms, f"{ts_name} - integration_platforms") platform_scope = platforms + integration_platforms else: platform_scope = platforms else: platform_scope = platforms integration = self.options.integration and ts.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if ts.platform_allow and not platform_filter and not integration and platform_config.get('increased_platform_scope', True): self.verify_platforms_existence( ts.platform_allow, f"{ts_name} - platform_allow") a = set(platform_scope) b = set(filter(lambda item: item.name in ts.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in ts.platform_allow, \ self.platforms)) # list of instances per testsuite, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(ts, plat, self.env.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.options.enable_slow, tfilter, self.options.fixture, self.hwm ) if not force_platform and plat.name in exclude_platform: instance.add_filter("Platform is excluded on command line.", Filters.CMD_LINE) if (plat.arch == "unit") != (ts.type == "unit"): # Discard silently continue if ts.modules and self.modules: if not set(ts.modules).issubset(set(self.modules)): instance.add_filter(f"one or more required modules not available: {','.join(ts.modules)}", Filters.MODULE) if self.options.level: tl = self.get_level(self.options.level) if tl is None: instance.add_filter(f"Unknown test level '{self.options.level}'", Filters.TESTPLAN) else: planned_scenarios = tl.scenarios if ts.id not in planned_scenarios and not set(ts.levels).intersection(set(tl.levels)): instance.add_filter("Not part of requested test plan", Filters.TESTPLAN) if runnable and not instance.run: instance.add_filter("Not runnable on device", Filters.CMD_LINE) if self.options.integration and ts.integration_platforms and plat.name not in ts.integration_platforms: instance.add_filter("Not part of integration platforms", Filters.TESTSUITE) if ts.skip: instance.add_filter("Skip filter", Filters.SKIP) if tag_filter and not ts.tags.intersection(tag_filter): instance.add_filter("Command line testsuite tag filter", Filters.CMD_LINE) if slow_only and not ts.slow: instance.add_filter("Not a slow test", Filters.CMD_LINE) if exclude_tag and ts.tags.intersection(exclude_tag): instance.add_filter("Command line testsuite exclude filter", Filters.CMD_LINE) if testsuite_filter: normalized_f = [os.path.basename(_ts) for _ts in testsuite_filter] if ts.id not in normalized_f: instance.add_filter("Testsuite name filter", Filters.CMD_LINE) if arch_filter and plat.arch not in arch_filter: instance.add_filter("Command line testsuite arch filter", Filters.CMD_LINE) if not force_platform: if ts.arch_allow and plat.arch not in ts.arch_allow: instance.add_filter("Not in test case arch allow list", Filters.TESTSUITE) if ts.arch_exclude and plat.arch in ts.arch_exclude: instance.add_filter("In test case arch exclude", Filters.TESTSUITE) if ts.platform_exclude and plat.name in ts.platform_exclude: instance.add_filter("In test case platform exclude", Filters.TESTSUITE) if ts.toolchain_exclude and toolchain in ts.toolchain_exclude: instance.add_filter("In test case toolchain exclude", Filters.TOOLCHAIN) if platform_filter and plat.name not in platform_filter: instance.add_filter("Command line platform filter", Filters.CMD_LINE) if ts.platform_allow \ and plat.name not in ts.platform_allow \ and not (platform_filter and force_platform): instance.add_filter("Not in testsuite platform allow list", Filters.TESTSUITE) if ts.platform_type and plat.type not in ts.platform_type: instance.add_filter("Not in testsuite platform type list", Filters.TESTSUITE) if ts.toolchain_allow and toolchain not in ts.toolchain_allow: instance.add_filter("Not in testsuite toolchain allow list", Filters.TOOLCHAIN) if not plat.env_satisfied: instance.add_filter("Environment ({}) not satisfied".format(", ".join(plat.env)), Filters.PLATFORM) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and "host" not in plat.supported_toolchains \ and ts.type != 'unit': instance.add_filter("Not supported by the toolchain", Filters.PLATFORM) if plat.ram < ts.min_ram: instance.add_filter("Not enough RAM", Filters.PLATFORM) if ts.harness: if ts.harness == 'robot' and plat.simulation != 'renode': instance.add_filter("No robot support for the selected platform", Filters.SKIP) if ts.depends_on: dep_intersection = ts.depends_on.intersection(set(plat.supported)) if dep_intersection != set(ts.depends_on): instance.add_filter("No hardware support", Filters.PLATFORM) if plat.flash < ts.min_flash: instance.add_filter("Not enough FLASH", Filters.PLATFORM) if set(plat.ignore_tags) & ts.tags: instance.add_filter("Excluded tags per platform (exclude_tags)", Filters.PLATFORM) if plat.only_tags and not set(plat.only_tags) & ts.tags: instance.add_filter("Excluded tags per platform (only_tags)", Filters.PLATFORM) if ts.required_snippets: missing_snippet = False snippet_args = {"snippets": ts.required_snippets} found_snippets = snippets.find_snippets_in_roots(snippet_args, [*self.env.snippet_roots, Path(ts.source_dir)]) # Search and check that all required snippet files are found for this_snippet in snippet_args['snippets']: if this_snippet not in found_snippets: logger.error(f"Can't find snippet '%s' for test '%s'", this_snippet, ts.name) instance.status = TwisterStatus.ERROR instance.reason = f"Snippet {this_snippet} not found" missing_snippet = True break if not missing_snippet: # Look for required snippets and check that they are applicable for these # platforms/boards for this_snippet in snippet_args['snippets']: matched_snippet_board = False # If the "appends" key is present with at least one entry then this # snippet applies to all boards and further platform-specific checks # are not required if found_snippets[this_snippet].appends: continue for this_board in found_snippets[this_snippet].board2appends: if this_board.startswith('/'): match = re.search(this_board[1:-1], plat.name) if match is not None: matched_snippet_board = True break elif this_board == plat.name: matched_snippet_board = True break if matched_snippet_board is False: instance.add_filter("Snippet not supported", Filters.PLATFORM) break # handle quarantined tests self.handle_quarantined_tests(instance, plat) # platform_key is a list of unique platform attributes that form a unique key a test # will match against to determine if it should be scheduled to run. A key containing a # field name that the platform does not have will filter the platform. # # A simple example is keying on arch and simulation # to run a test once per unique (arch, simulation) platform. if not ignore_platform_key and hasattr(ts, 'platform_key') and len(ts.platform_key) > 0: key_fields = sorted(set(ts.platform_key)) keys = [getattr(plat, key_field) for key_field in key_fields] for key in keys: if key is None or key == 'na': instance.add_filter( f"Excluded platform missing key fields demanded by test {key_fields}", Filters.PLATFORM ) break else: test_keys = copy.deepcopy(keys) test_keys.append(ts.name) test_keys = tuple(test_keys) keyed_test = keyed_tests.get(test_keys) if keyed_test is not None: plat_key = {key_field: getattr(keyed_test['plat'], key_field) for key_field in key_fields} instance.add_filter(f"Already covered for key {tuple(key)} by platform {keyed_test['plat'].name} having key {plat_key}", Filters.PLATFORM_KEY) else: # do not add a platform to keyed tests if previously filtered if not instance.filters: keyed_tests[test_keys] = {'plat': plat, 'ts': ts} else: instance.add_filter(f"Excluded platform missing key fields demanded by test {key_fields}", Filters.PLATFORM) # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testsuite if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not ts.build_on_all and not integration: if ts.platform_allow: a = set(self.default_platforms) b = set(ts.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda ts: ts.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: # add integration platforms to the list of default # platforms, even if we are not in integration mode _platforms = self.default_platforms + ts.integration_platforms instances = list(filter(lambda ts: ts.platform.name in _platforms, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in ts.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): instance.add_filter("Not an emulated platform", Filters.CMD_LINE) elif vendor_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.vendor in vendor_filter, instance_list)): instance.add_filter("Not a selected vendor platform", Filters.CMD_LINE) else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.options.enable_asan, self.options.enable_ubsan, self.options.enable_coverage, self.options.coverage_platform) self.selected_platforms = set(p.platform.name for p in self.instances.values()) filtered_instances = list(filter(lambda item: item.status == TwisterStatus.FILTER, self.instances.values())) for filtered_instance in filtered_instances: change_skip_to_error_if_integration(self.options, filtered_instance) filtered_instance.add_missing_case_status(filtered_instance.status) self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != TwisterStatus.SKIP ) def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance def get_testsuite(self, identifier): results = [] for _, ts in self.testsuites.items(): for case in ts.testcases: if case.name == identifier: results.append(ts) return results def verify_platforms_existence(self, platform_names_to_verify, log_info=""): """ Verify if platform name (passed by --platform option, or in yaml file as platform_allow or integration_platforms options) is correct. If not - log and raise error. """ for platform in platform_names_to_verify: if platform in self.platform_names: continue else: logger.error(f"{log_info} - unrecognized platform - {platform}") sys.exit(2) def create_build_dir_links(self): """ Iterate through all no-skipped instances in suite and create links for each one build directories. Those links will be passed in the next steps to the CMake command. """ links_dir_name = "twister_links" # folder for all links links_dir_path = os.path.join(self.env.outdir, links_dir_name) if not os.path.exists(links_dir_path): os.mkdir(links_dir_path) for instance in self.instances.values(): if instance.status != TwisterStatus.SKIP: self._create_build_dir_link(links_dir_path, instance) def _create_build_dir_link(self, links_dir_path, instance): """ Create build directory with original "long" path. Next take shorter path and link them with original path - create link. At the end replace build_dir to created link. This link will be passed to CMake command. This action helps to limit path length which can be significant during building by CMake on Windows OS. """ os.makedirs(instance.build_dir, exist_ok=True) link_name = f"test_{self.link_dir_counter}" link_path = os.path.join(links_dir_path, link_name) if os.name == "nt": # if OS is Windows command = ["mklink", "/J", f"{link_path}", os.path.normpath(instance.build_dir)] subprocess.call(command, shell=True) else: # for Linux and MAC OS os.symlink(instance.build_dir, link_path) # Here original build directory is replaced with symbolic link. It will # be passed to CMake command instance.build_dir = link_path self.link_dir_counter += 1 def change_skip_to_error_if_integration(options, instance): ''' All skips on integration_platforms are treated as errors.''' if instance.platform.name in instance.testsuite.integration_platforms: # Do not treat this as error if filter type is among ignore_filters filters = {t['type'] for t in instance.filters} ignore_filters ={Filters.CMD_LINE, Filters.SKIP, Filters.PLATFORM_KEY, Filters.TOOLCHAIN, Filters.MODULE, Filters.TESTPLAN, Filters.QUARANTINE} if filters.intersection(ignore_filters): return instance.status = TwisterStatus.ERROR instance.reason += " but is one of the integration platforms" ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/testplan.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,577
```python # vim: set syntax=python ts=4 : # import copy import scl import warnings from typing import Union from twisterlib.error import ConfigurationError def extract_fields_from_arg_list(target_fields: set, arg_list: Union[str, list]): """ Given a list of "FIELD=VALUE" args, extract values of args with a given field name and return the remaining args separately. """ extracted_fields = {f : list() for f in target_fields} other_fields = [] if isinstance(arg_list, str): args = arg_list.strip().split() else: args = arg_list for field in args: try: name, val = field.split("=", 1) except ValueError: # Can't parse this. Just pass it through other_fields.append(field) continue if name in target_fields: extracted_fields[name].append(val.strip('\'"')) else: # Move to other_fields other_fields.append(field) return extracted_fields, " ".join(other_fields) class TwisterConfigParser: """Class to read testsuite yaml files with semantic checking """ testsuite_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "extra_conf_files": {"type": "list", "default": []}, "extra_overlay_confs" : {"type": "list", "default": []}, "extra_dtc_overlay_files": {"type": "list", "default": []}, "required_snippets": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "modules": {"type": "list", "default": []}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "ignore_faults": {"type": "bool", "default": False }, "ignore_qemu_crash": {"type": "bool", "default": False }, "testcases": {"type": "list", "default": []}, "platform_type": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "platform_key": {"type": "list", "default": []}, "simulation_exclude": {"type": "list", "default": []}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "levels": {"type": "list", "default": []}, "harness": {"type": "str", "default": "test"}, "harness_config": {"type": "map", "default": {}}, "seed": {"type": "int", "default": 0}, "sysbuild": {"type": "bool", "default": False} } def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.scenarios = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.scenarios = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list"): if isinstance(value, list): return value elif isinstance(value, str): vs = v.split() if len(vs) > 1: warnings.warn( "Space-separated lists are deprecated, use YAML lists instead", DeprecationWarning) if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs else: raise ValueError elif typestr.startswith("set"): if isinstance(value, list): return set(value) elif isinstance(value, str): vs = v.split() if len(vs) > 1: warnings.warn( "Space-separated lists are deprecated, use YAML lists instead", DeprecationWarning) if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) else: raise ValueError elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_scenario(self, name): """Get a dictionary representing the keys/values within a scenario @param name The scenario in the .yaml file to retrieve data from @return A dictionary containing the scenario key-value pairs with type conversion and default values filled in per valid_keys """ # "CONF_FILE", "OVERLAY_CONFIG", and "DTC_OVERLAY_FILE" fields from each # of the extra_args lines extracted_common = {} extracted_testsuite = {} d = {} for k, v in self.common.items(): if k == "extra_args": # Pull out these fields and leave the rest extracted_common, d[k] = extract_fields_from_arg_list( {"CONF_FILE", "OVERLAY_CONFIG", "DTC_OVERLAY_FILE"}, v ) else: # Copy common value to avoid mutating it with test specific values below d[k] = copy.copy(v) for k, v in self.scenarios[name].items(): if k == "extra_args": # Pull out these fields and leave the rest extracted_testsuite, v = extract_fields_from_arg_list( {"CONF_FILE", "OVERLAY_CONFIG", "DTC_OVERLAY_FILE"}, v ) if k in d: if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) elif k not in ("extra_conf_files", "extra_overlay_confs", "extra_dtc_overlay_files"): if isinstance(d[k], str) and isinstance(v, list): d[k] = d[k].split() + v elif isinstance(d[k], list) and isinstance(v, str): d[k] += v.split() elif isinstance(d[k], list) and isinstance(v, list): d[k] += v elif isinstance(d[k], str) and isinstance(v, str): d[k] += " " + v else: # replace value if not str/list (e.g. integer) d[k] = v else: d[k] = v # Compile conf files in to a single list. The order to apply them is: # (1) CONF_FILEs extracted from common['extra_args'] # (2) common['extra_conf_files'] # (3) CONF_FILES extracted from scenarios[name]['extra_args'] # (4) scenarios[name]['extra_conf_files'] d["extra_conf_files"] = \ extracted_common.get("CONF_FILE", []) + \ self.common.get("extra_conf_files", []) + \ extracted_testsuite.get("CONF_FILE", []) + \ self.scenarios[name].get("extra_conf_files", []) # Repeat the above for overlay confs and DTC overlay files d["extra_overlay_confs"] = \ extracted_common.get("OVERLAY_CONFIG", []) + \ self.common.get("extra_overlay_confs", []) + \ extracted_testsuite.get("OVERLAY_CONFIG", []) + \ self.scenarios[name].get("extra_overlay_confs", []) d["extra_dtc_overlay_files"] = \ extracted_common.get("DTC_OVERLAY_FILE", []) + \ self.common.get("extra_dtc_overlay_files", []) + \ extracted_testsuite.get("DTC_OVERLAY_FILE", []) + \ self.scenarios[name].get("extra_dtc_overlay_files", []) if any({len(x) > 0 for x in extracted_common.values()}) or \ any({len(x) > 0 for x in extracted_testsuite.values()}): warnings.warn( "Do not specify CONF_FILE, OVERLAY_CONFIG, or DTC_OVERLAY_FILE " "in extra_args. This feature is deprecated and will soon " "result in an error. Use extra_conf_files, extra_overlay_confs " "or extra_dtc_overlay_files YAML fields instead", DeprecationWarning ) for k, kinfo in self.testsuite_valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/config_parser.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,307
```python # vim: set syntax=python ts=4 : # import logging import multiprocessing import os import pickle import queue import re import shutil import subprocess import sys import time import traceback import yaml from multiprocessing import Lock, Process, Value from multiprocessing.managers import BaseManager from typing import List from packaging import version from colorama import Fore from domains import Domains from twisterlib.cmakecache import CMakeCache from twisterlib.environment import canonical_zephyr_base from twisterlib.error import BuildError, ConfigurationError from twisterlib.statuses import TwisterStatus import elftools from elftools.elf.elffile import ELFFile from elftools.elf.sections import SymbolTableSection if version.parse(elftools.__version__) < version.parse('0.24'): sys.exit("pyelftools is out of date, need version 0.24 or later") # Job server only works on Linux for now. if sys.platform == 'linux': from twisterlib.jobserver import GNUMakeJobClient, GNUMakeJobServer, JobClient from twisterlib.log_helper import log_command from twisterlib.testinstance import TestInstance from twisterlib.environment import TwisterEnv from twisterlib.testsuite import TestSuite from twisterlib.platform import Platform from twisterlib.testplan import change_skip_to_error_if_integration from twisterlib.harness import HarnessImporter, Pytest try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) import expr_parser class ExecutionCounter(object): def __init__(self, total=0): ''' Most of the stats are at test instance level Except that "_cases" and "_skipped_cases" are for cases of ALL test instances total complete = done + skipped_filter total = yaml test scenarios * applicable platforms complete perctenage = (done + skipped_filter) / total pass rate = passed / (total - skipped_configs) ''' # instances that go through the pipeline # updated by report_out() self._done = Value('i', 0) # iteration self._iteration = Value('i', 0) # instances that actually executed and passed # updated by report_out() self._passed = Value('i', 0) # static filter + runtime filter + build skipped # updated by update_counting_before_pipeline() and report_out() self._skipped_configs = Value('i', 0) # cmake filter + build skipped # updated by report_out() self._skipped_runtime = Value('i', 0) # staic filtered at yaml parsing time # updated by update_counting_before_pipeline() self._skipped_filter = Value('i', 0) # updated by update_counting_before_pipeline() and report_out() self._skipped_cases = Value('i', 0) # updated by report_out() in pipeline self._error = Value('i', 0) self._failed = Value('i', 0) # initialized to number of test instances self._total = Value('i', total) # updated in report_out self._cases = Value('i', 0) self.lock = Lock() def summary(self): print("--------------------------------") print(f"Total test suites: {self.total}") # actually test instances print(f"Total test cases: {self.cases}") print(f"Executed test cases: {self.cases - self.skipped_cases}") print(f"Skipped test cases: {self.skipped_cases}") print(f"Completed test suites: {self.done}") print(f"Passing test suites: {self.passed}") print(f"Failing test suites: {self.failed}") print(f"Skipped test suites: {self.skipped_configs}") print(f"Skipped test suites (runtime): {self.skipped_runtime}") print(f"Skipped test suites (filter): {self.skipped_filter}") print(f"Errors: {self.error}") print("--------------------------------") @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def iteration(self): with self._iteration.get_lock(): return self._iteration.value @iteration.setter def iteration(self, value): with self._iteration.get_lock(): self._iteration.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_filter(self): with self._skipped_filter.get_lock(): return self._skipped_filter.value @skipped_filter.setter def skipped_filter(self, value): with self._skipped_filter.get_lock(): self._skipped_filter.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMake: config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testsuite: TestSuite, platform: Platform, source_dir, build_dir, jobserver): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testsuite = testsuite self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.default_encoding = sys.getdefaultencoding() self.jobserver = jobserver def parse_generated(self, filter_stages=[]): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd start_time = time.time() if sys.platform == 'linux': p = self.jobserver.popen(cmd, **kwargs) else: p = subprocess.Popen(cmd, **kwargs) logger.debug(f'Running {" ".join(cmd)}') out, _ = p.communicate() ret = {} duration = time.time() - start_time self.instance.build_time += duration if p.returncode == 0: msg = f"Finished building {self.source_dir} for {self.platform.name} in {duration:.2f} seconds" logger.debug(msg) self.instance.status = TwisterStatus.PASS if not self.instance.run: self.instance.add_missing_case_status(TwisterStatus.SKIP, "Test was built only") ret = {"returncode": p.returncode} if out: log_msg = out.decode(self.default_encoding) with open(os.path.join(self.build_dir, self.log), "a", encoding=self.default_encoding) as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(self.default_encoding) with open(os.path.join(self.build_dir, self.log), "a", encoding=self.default_encoding) as log: log.write(log_msg) if log_msg: overflow_found = re.findall("region `(FLASH|ROM|RAM|ICCM|DCCM|SRAM|dram\\d_\\d_seg)' overflowed by", log_msg) imgtool_overflow_found = re.findall(r"Error: Image size \(.*\) \+ trailer \(.*\) exceeds requested size", log_msg) if overflow_found and not self.options.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(overflow_found[0])) self.instance.status = TwisterStatus.SKIP self.instance.reason = "{} overflow".format(overflow_found[0]) change_skip_to_error_if_integration(self.options, self.instance) elif imgtool_overflow_found and not self.options.overflow_as_errors: self.instance.status = TwisterStatus.SKIP self.instance.reason = "imgtool overflow" change_skip_to_error_if_integration(self.options, self.instance) else: self.instance.status = TwisterStatus.ERROR self.instance.reason = "Build failure" ret = { "returncode": p.returncode } return ret def run_cmake(self, args="", filter_stages=[]): if not self.options.disable_warnings_as_errors: warnings_as_errors = 'y' gen_defines_args = "--edtlib-Werror" else: warnings_as_errors = 'n' gen_defines_args = "" warning_command = 'CONFIG_COMPILER_WARNINGS_AS_ERRORS' if self.instance.sysbuild: warning_command = 'SB_' + warning_command logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-DTC_RUNID={self.instance.run_id}', f'-D{warning_command}={warnings_as_errors}', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.env.generator}' ] # If needed, run CMake using the package_helper script first, to only run # a subset of all cmake modules. This output will be used to filter # testcases, and the full CMake configuration will be run for # testcases that should be built if filter_stages: cmake_filter_args = [ f'-DMODULES={",".join(filter_stages)}', f'-P{canonical_zephyr_base}/cmake/package_helper.cmake', ] if self.instance.sysbuild and not filter_stages: logger.debug("Building %s using sysbuild" % (self.source_dir)) source_args = [ f'-S{canonical_zephyr_base}/share/sysbuild', f'-DAPP_DIR={self.source_dir}' ] else: source_args = [ f'-S{self.source_dir}' ] cmake_args.extend(source_args) cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) if self.instance.testsuite.required_snippets: cmake_opts = ['-DSNIPPET={}'.format(';'.join(self.instance.testsuite.required_snippets))] cmake_args.extend(cmake_opts) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args if filter_stages: cmd += cmake_filter_args kwargs = dict() log_command(logger, "Calling cmake", cmd) if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd start_time = time.time() if sys.platform == 'linux': p = self.jobserver.popen(cmd, **kwargs) else: p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() duration = time.time() - start_time self.instance.build_time += duration if p.returncode == 0: filter_results = self.parse_generated(filter_stages) msg = f"Finished running cmake {self.source_dir} for {self.platform.name} in {duration:.2f} seconds" logger.debug(msg) ret = { 'returncode': p.returncode, 'filter': filter_results } else: self.instance.status = TwisterStatus.ERROR self.instance.reason = "Cmake build failure" for tc in self.instance.testcases: tc.status = self.instance.status logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) ret = {"returncode": p.returncode} if out: os.makedirs(self.build_dir, exist_ok=True) with open(os.path.join(self.build_dir, self.log), "a", encoding=self.default_encoding) as log: log_msg = out.decode(self.default_encoding) log.write(log_msg) return ret class FilterBuilder(CMake): def __init__(self, testsuite: TestSuite, platform: Platform, source_dir, build_dir, jobserver): super().__init__(testsuite, platform, source_dir, build_dir, jobserver) self.log = "config-twister.log" def parse_generated(self, filter_stages=[]): if self.platform.name == "unit_testing": return {} if self.instance.sysbuild and not filter_stages: # Load domain yaml to get default domain build directory domain_path = os.path.join(self.build_dir, "domains.yaml") domains = Domains.from_file(domain_path) logger.debug("Loaded sysbuild domain data from %s" % (domain_path)) self.instance.domains = domains domain_build = domains.get_default_domain().build_dir cmake_cache_path = os.path.join(domain_build, "CMakeCache.txt") defconfig_path = os.path.join(domain_build, "zephyr", ".config") edt_pickle = os.path.join(domain_build, "zephyr", "edt.pickle") else: cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") # .config is only available after kconfig stage in cmake. If only dt based filtration is required # package helper call won't produce .config if not filter_stages or "kconfig" in filter_stages: defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") # dt is compiled before kconfig, so edt_pickle is available regardless of choice of filter stages edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if not filter_stages or "kconfig" in filter_stages: with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) if not filter_stages or "kconfig" in filter_stages: filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) if self.instance.sysbuild and self.env.options.device_testing: # Verify that twister's arguments support sysbuild. # Twister sysbuild flashing currently only works with west, so # --west-flash must be passed. if self.env.options.west_flash is None: logger.warning("Sysbuild test will be skipped. " + "West must be used for flashing.") return {os.path.join(self.platform.name, self.testsuite.name): True} if self.testsuite and self.testsuite.filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None ret = expr_parser.parse(self.testsuite.filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testsuite.yamlfile) raise se if not ret: return {os.path.join(self.platform.name, self.testsuite.name): True} else: return {os.path.join(self.platform.name, self.testsuite.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, instance: TestInstance, env: TwisterEnv, jobserver, **kwargs): super().__init__(instance.testsuite, instance.platform, instance.testsuite.source_dir, instance.build_dir, jobserver) self.log = "build.log" self.instance = instance self.filtered_tests = 0 self.options = env.options self.env = env self.duts = None def log_info(self, filename, inline_logs, log_testcases=False): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) # Remove any coverage data from the dumped logs data = re.sub( r"GCOV_COVERAGE_DUMP_START.*GCOV_COVERAGE_DUMP_END", "GCOV_COVERAGE_DUMP_START\n...\nGCOV_COVERAGE_DUMP_END", data, flags=re.DOTALL, ) logger.error(data) logger.info("{:-^100}".format(filename)) if log_testcases: for tc in self.instance.testcases: if not tc.reason: continue logger.info( f"\n{str(tc.name).center(100, '_')}\n" f"{tc.reason}\n" f"{100*'_'}\n" f"{tc.output}" ) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) he_log = "{}/handler_stderr.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) pytest_log = "{}/twister_harness.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(pytest_log) and os.path.getsize(pytest_log) > 0: self.log_info("{}".format(pytest_log), inline_logs, log_testcases=True) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(he_log) and os.path.getsize(he_log) > 0: self.log_info("{}".format(he_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def process(self, pipeline, done, message, lock, results): op = message.get('op') self.instance.setup_handler(self.env) if op == "filter": ret = self.cmake(filter_stages=self.instance.filter_stages) if self.instance.status in [TwisterStatus.FAIL, TwisterStatus.ERROR]: pipeline.put({"op": "report", "test": self.instance}) else: # Here we check the dt/kconfig filter results coming from running cmake if self.instance.name in ret['filter'] and ret['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = TwisterStatus.FILTER self.instance.reason = "runtime filter" results.skipped_runtime += 1 self.instance.add_missing_case_status(TwisterStatus.SKIP) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "cmake", "test": self.instance}) # The build process, call cmake and build with configured generator elif op == "cmake": ret = self.cmake() if self.instance.status in [TwisterStatus.FAIL, TwisterStatus.ERROR]: pipeline.put({"op": "report", "test": self.instance}) elif self.options.cmake_only: if self.instance.status == TwisterStatus.NONE: self.instance.status = TwisterStatus.PASS pipeline.put({"op": "report", "test": self.instance}) else: # Here we check the runtime filter results coming from running cmake if self.instance.name in ret['filter'] and ret['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = TwisterStatus.FILTER self.instance.reason = "runtime filter" results.skipped_runtime += 1 self.instance.add_missing_case_status(TwisterStatus.SKIP) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) ret = self.build() if not ret: self.instance.status = TwisterStatus.ERROR self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. if self.instance.status == TwisterStatus.SKIP: results.skipped_runtime += 1 self.instance.add_missing_case_status(TwisterStatus.SKIP, self.instance.reason) if ret.get('returncode', 1) > 0: self.instance.add_missing_case_status(TwisterStatus.BLOCK, self.instance.reason) pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.testsuite.harness in ['ztest', 'test']: logger.debug(f"Determine test cases for test instance: {self.instance.name}") try: self.determine_testcases(results) pipeline.put({"op": "gather_metrics", "test": self.instance}) except BuildError as e: logger.error(str(e)) self.instance.status = TwisterStatus.ERROR self.instance.reason = str(e) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "gather_metrics", "test": self.instance}) elif op == "gather_metrics": ret = self.gather_metrics(self.instance) if not ret or ret.get('returncode', 1) > 0: self.instance.status = TwisterStatus.ERROR self.instance.reason = "Build Failure at gather_metrics." pipeline.put({"op": "report", "test": self.instance}) elif self.instance.run and self.instance.handler.ready: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() logger.debug(f"run status: {self.instance.name} {self.instance.status}") try: # to make it work with pickle self.instance.handler.thread = None self.instance.handler.duts = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) except RuntimeError as e: logger.error(f"RuntimeError: {e}") traceback.print_exc() # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if not self.options.coverage: if self.options.prep_artifacts_for_testing: pipeline.put({"op": "cleanup", "mode": "device", "test": self.instance}) elif self.options.runtime_artifact_cleanup == "pass" and self.instance.status == TwisterStatus.PASS: pipeline.put({"op": "cleanup", "mode": "passed", "test": self.instance}) elif self.options.runtime_artifact_cleanup == "all": pipeline.put({"op": "cleanup", "mode": "all", "test": self.instance}) elif op == "cleanup": mode = message.get("mode") if mode == "device": self.cleanup_device_testing_artifacts() elif mode == "passed" or (mode == "all" and self.instance.reason != "Cmake build failure"): self.cleanup_artifacts() def determine_testcases(self, results): yaml_testsuite_name = self.instance.testsuite.id logger.debug(f"Determine test cases for test suite: {yaml_testsuite_name}") elf_file = self.instance.get_elf_file() elf = ELFFile(open(elf_file, "rb")) logger.debug(f"Test instance {self.instance.name} already has {len(self.instance.testcases)} cases.") new_ztest_unit_test_regex = re.compile(r"z_ztest_unit_test__([^\s]+?)__([^\s]*)") detected_cases = [] for section in elf.iter_sections(): if isinstance(section, SymbolTableSection): for sym in section.iter_symbols(): # It is only meant for new ztest fx because only new ztest fx exposes test functions # precisely. # The 1st capture group is new ztest suite name. # The 2nd capture group is new ztest unit test name. matches = new_ztest_unit_test_regex.findall(sym.name) if matches: for m in matches: # new_ztest_suite = m[0] # not used for now test_func_name = m[1].replace("test_", "", 1) testcase_id = f"{yaml_testsuite_name}.{test_func_name}" detected_cases.append(testcase_id) if detected_cases: logger.debug(f"{', '.join(detected_cases)} in {elf_file}") self.instance.testcases.clear() self.instance.testsuite.testcases.clear() # When the old regex-based test case collection is fully deprecated, # this will be the sole place where test cases get added to the test instance. # Then we can further include the new_ztest_suite info in the testcase_id. for testcase_id in detected_cases: self.instance.add_testcase(name=testcase_id) self.instance.testsuite.add_testcase(name=testcase_id) def cleanup_artifacts(self, additional_keep: List[str] = []): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ os.path.join('zephyr', '.config'), 'handler.log', 'handler_stderr.log', 'build.log', 'device.log', 'recording.csv', 'rom.json', 'ram.json', # below ones are needed to make --test-only work as well 'Makefile', 'CMakeCache.txt', 'build.ninja', os.path.join('CMakeFiles', 'rules.ninja') ] allow += additional_keep if self.options.runtime_artifact_cleanup == 'all': allow += [os.path.join('twister', 'testsuite_extra.conf')] allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) files_to_keep = self._get_binaries() files_to_keep.append(os.path.join('zephyr', 'runners.yaml')) if self.instance.sysbuild: files_to_keep.append('domains.yaml') for domain in self.instance.domains.get_domains(): files_to_keep += self._get_artifact_allow_list_for_domain(domain.name) self.cleanup_artifacts(files_to_keep) self._sanitize_files() def _get_artifact_allow_list_for_domain(self, domain: str) -> List[str]: """ Return a list of files needed to test a given domain. """ allow = [ os.path.join(domain, 'build.ninja'), os.path.join(domain, 'CMakeCache.txt'), os.path.join(domain, 'CMakeFiles', 'rules.ninja'), os.path.join(domain, 'Makefile'), os.path.join(domain, 'zephyr', '.config'), os.path.join(domain, 'zephyr', 'runners.yaml') ] return allow def _get_binaries(self) -> List[str]: """ Get list of binaries paths (absolute or relative to the self.instance.build_dir), basing on information from platform.binaries or runners.yaml. If they are not found take default binaries like "zephyr/zephyr.hex" etc. """ binaries: List[str] = [] platform = self.instance.platform if platform.binaries: for binary in platform.binaries: binaries.append(os.path.join('zephyr', binary)) # Get binaries for a single-domain build binaries += self._get_binaries_from_runners() # Get binaries in the case of a multiple-domain build if self.instance.sysbuild: for domain in self.instance.domains.get_domains(): binaries += self._get_binaries_from_runners(domain.name) # if binaries was not found in platform.binaries and runners.yaml take default ones if len(binaries) == 0: binaries = [ os.path.join('zephyr', 'zephyr.hex'), os.path.join('zephyr', 'zephyr.bin'), os.path.join('zephyr', 'zephyr.elf'), os.path.join('zephyr', 'zephyr.exe'), ] return binaries def _get_binaries_from_runners(self, domain='') -> List[str]: """ Get list of binaries paths (absolute or relative to the self.instance.build_dir) from runners.yaml file. May be used for multiple-domain builds by passing in one domain at a time. """ runners_file_path: str = os.path.join(self.instance.build_dir, domain, 'zephyr', 'runners.yaml') if not os.path.exists(runners_file_path): return [] with open(runners_file_path, 'r') as file: runners_content: dict = yaml.load(file, Loader=SafeLoader) if 'config' not in runners_content: return [] runners_config: dict = runners_content['config'] binary_keys: List[str] = ['elf_file', 'hex_file', 'bin_file'] binaries: List[str] = [] for binary_key in binary_keys: binary_path = runners_config.get(binary_key) if binary_path is None: continue if os.path.isabs(binary_path): binaries.append(binary_path) else: binaries.append(os.path.join(domain, 'zephyr', binary_path)) return binaries def _sanitize_files(self): """ Sanitize files to make it possible to flash those file on different computer/system. """ self._sanitize_runners_file() self._sanitize_zephyr_base_from_files() def _sanitize_runners_file(self): """ Replace absolute paths of binary files for relative ones. The base directory for those files is f"{self.instance.build_dir}/zephyr" """ runners_dir_path: str = os.path.join(self.instance.build_dir, 'zephyr') runners_file_path: str = os.path.join(runners_dir_path, 'runners.yaml') if not os.path.exists(runners_file_path): return with open(runners_file_path, 'rt') as file: runners_content_text = file.read() runners_content_yaml: dict = yaml.load(runners_content_text, Loader=SafeLoader) if 'config' not in runners_content_yaml: return runners_config: dict = runners_content_yaml['config'] binary_keys: List[str] = ['elf_file', 'hex_file', 'bin_file'] for binary_key in binary_keys: binary_path = runners_config.get(binary_key) # sanitize only paths which exist and are absolute if binary_path is None or not os.path.isabs(binary_path): continue binary_path_relative = os.path.relpath(binary_path, start=runners_dir_path) runners_content_text = runners_content_text.replace(binary_path, binary_path_relative) with open(runners_file_path, 'wt') as file: file.write(runners_content_text) def _sanitize_zephyr_base_from_files(self): """ Remove Zephyr base paths from selected files. """ files_to_sanitize = [ 'CMakeCache.txt', os.path.join('zephyr', 'runners.yaml'), ] for file_path in files_to_sanitize: file_path = os.path.join(self.instance.build_dir, file_path) if not os.path.exists(file_path): continue with open(file_path, "rt") as file: data = file.read() # add trailing slash at the end of canonical_zephyr_base if it does not exist: path_to_remove = os.path.join(canonical_zephyr_base, "") data = data.replace(path_to_remove, "") with open(file_path, "wt") as file: file.write(data) def report_out(self, results): total_to_do = results.total total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if results.iteration == 1: results.cases += len(instance.testcases) if instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: if instance.status == TwisterStatus.ERROR: results.error += 1 txt = " ERROR " else: results.failed += 1 txt = " FAILED " if self.options.verbose: status = Fore.RED + txt + Fore.RESET + instance.reason else: logger.error( "{:<25} {:<50} {}{}{}: {}".format( instance.platform.name, instance.testsuite.name, Fore.RED, txt, Fore.RESET, instance.reason)) if not self.options.verbose: self.log_info_file(self.options.inline_logs) elif instance.status in [TwisterStatus.SKIP, TwisterStatus.FILTER]: status = Fore.YELLOW + "SKIPPED" + Fore.RESET results.skipped_configs += 1 # test cases skipped at the test instance level results.skipped_cases += len(instance.testsuite.testcases) elif instance.status == TwisterStatus.PASS: status = Fore.GREEN + "PASSED" + Fore.RESET results.passed += 1 for case in instance.testcases: # test cases skipped at the test case level if case.status == TwisterStatus.SKIP: results.skipped_cases += 1 else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.options.verbose: if self.options.cmake_only: more_info = "cmake" elif instance.status in [TwisterStatus.SKIP, TwisterStatus.FILTER]: more_info = instance.reason else: if instance.handler.ready and instance.run: more_info = instance.handler.type_str htime = instance.execution_time if instance.dut: more_info += f": {instance.dut}," if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" if ( instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL] and hasattr(self.instance.handler, 'seed') and self.instance.handler.seed is not None ): more_info += "/seed: " + str(self.options.seed) logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do , instance.platform.name, instance.testsuite.name, status, more_info)) if instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: self.log_info_file(self.options.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) sys.stdout.write("INFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s, error: %s%4d%s\r" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if results.skipped_configs > 0 else Fore.RESET, results.skipped_configs, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET, Fore.RED if results.error > 0 else Fore.RESET, results.error, Fore.RESET ) ) sys.stdout.flush() @staticmethod def cmake_assemble_args(extra_args, handler, extra_conf_files, extra_overlay_confs, extra_dtc_overlay_files, cmake_extra_args, build_dir): # Retain quotes around config options config_options = [arg for arg in extra_args if arg.startswith("CONFIG_")] args = [arg for arg in extra_args if not arg.startswith("CONFIG_")] args_expanded = ["-D{}".format(a.replace('"', '\"')) for a in config_options] if handler.ready: args.extend(handler.args) if extra_conf_files: args.append(f"CONF_FILE=\"{';'.join(extra_conf_files)}\"") if extra_dtc_overlay_files: args.append(f"DTC_OVERLAY_FILE=\"{';'.join(extra_dtc_overlay_files)}\"") # merge overlay files into one variable overlays = extra_overlay_confs.copy() additional_overlay_path = os.path.join( build_dir, "twister", "testsuite_extra.conf" ) if os.path.exists(additional_overlay_path): overlays.append(additional_overlay_path) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) # Build the final argument list args_expanded.extend(["-D{}".format(a.replace('"', '\"')) for a in cmake_extra_args]) args_expanded.extend(["-D{}".format(a.replace('"', '')) for a in args]) return args_expanded def cmake(self, filter_stages=[]): args = self.cmake_assemble_args( self.testsuite.extra_args.copy(), # extra_args from YAML self.instance.handler, self.testsuite.extra_conf_files, self.testsuite.extra_overlay_confs, self.testsuite.extra_dtc_overlay_files, self.options.extra_args, # CMake extra args self.instance.build_dir, ) return self.run_cmake(args,filter_stages) def build(self): harness = HarnessImporter.get_harness(self.instance.testsuite.harness.capitalize()) build_result = self.run_build(['--build', self.build_dir]) try: if harness: harness.instance = self.instance harness.build() except ConfigurationError as error: self.instance.status = TwisterStatus.ERROR self.instance.reason = str(error) logger.error(self.instance.reason) return return build_result def run(self): instance = self.instance if instance.handler.ready: logger.debug(f"Reset instance status from '{instance.status}' to None before run.") instance.status = TwisterStatus.NONE if instance.handler.type_str == "device": instance.handler.duts = self.duts if(self.options.seed is not None and instance.platform.name.startswith("native_")): self.parse_generated() if('CONFIG_FAKE_ENTROPY_NATIVE_POSIX' in self.defconfig and self.defconfig['CONFIG_FAKE_ENTROPY_NATIVE_POSIX'] == 'y'): instance.handler.seed = self.options.seed if self.options.extra_test_args and instance.platform.arch == "posix": instance.handler.extra_test_args = self.options.extra_test_args harness = HarnessImporter.get_harness(instance.testsuite.harness.capitalize()) try: harness.configure(instance) except ConfigurationError as error: instance.status = TwisterStatus.ERROR instance.reason = str(error) logger.error(instance.reason) return # if isinstance(harness, Pytest): harness.pytest_run(instance.handler.get_test_timeout()) else: instance.handler.handle(harness) sys.stdout.flush() def gather_metrics(self, instance: TestInstance): build_result = {"returncode": 0} if self.options.create_rom_ram_report: build_result = self.run_build(['--build', self.build_dir, "--target", "footprint"]) if self.options.enable_size_report and not self.options.cmake_only: self.calc_size(instance=instance, from_buildlog=self.options.footprint_from_buildlog) else: instance.metrics["used_ram"] = 0 instance.metrics["used_rom"] = 0 instance.metrics["available_rom"] = 0 instance.metrics["available_ram"] = 0 instance.metrics["unrecognized"] = [] return build_result @staticmethod def calc_size(instance: TestInstance, from_buildlog: bool): if instance.status not in [TwisterStatus.ERROR, TwisterStatus.FAIL, TwisterStatus.SKIP]: if not instance.platform.type in ["native", "qemu", "unit"]: generate_warning = bool(instance.platform.type == "mcu") size_calc = instance.calculate_sizes(from_buildlog=from_buildlog, generate_warning=generate_warning) instance.metrics["used_ram"] = size_calc.get_used_ram() instance.metrics["used_rom"] = size_calc.get_used_rom() instance.metrics["available_rom"] = size_calc.get_available_rom() instance.metrics["available_ram"] = size_calc.get_available_ram() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["used_ram"] = 0 instance.metrics["used_rom"] = 0 instance.metrics["available_rom"] = 0 instance.metrics["available_ram"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.execution_time class TwisterRunner: def __init__(self, instances, suites, env=None) -> None: self.pipeline = None self.options = env.options self.env = env self.instances = instances self.suites = suites self.duts = None self.jobs = 1 self.results = None self.jobserver = None def run(self): retries = self.options.retry_failed + 1 BaseManager.register('LifoQueue', queue.LifoQueue) manager = BaseManager() manager.start() self.results = ExecutionCounter(total=len(self.instances)) self.iteration = 0 pipeline = manager.LifoQueue() done_queue = manager.LifoQueue() # Set number of jobs if self.options.jobs: self.jobs = self.options.jobs elif self.options.build_only: self.jobs = multiprocessing.cpu_count() * 2 else: self.jobs = multiprocessing.cpu_count() if sys.platform == "linux": if os.name == 'posix': self.jobserver = GNUMakeJobClient.from_environ(jobs=self.options.jobs) if not self.jobserver: self.jobserver = GNUMakeJobServer(self.jobs) elif self.jobserver.jobs: self.jobs = self.jobserver.jobs # TODO: Implement this on windows/mac also else: self.jobserver = JobClient() logger.info("JOBS: %d", self.jobs) self.update_counting_before_pipeline() while True: self.results.iteration += 1 if self.results.iteration > 1: logger.info("%d Iteration:" % (self.results.iteration)) time.sleep(self.options.retry_interval) # waiting for the system to settle down self.results.done = self.results.total - self.results.failed - self.results.error self.results.failed = 0 if self.options.retry_build_errors: self.results.error = 0 else: self.results.done = self.results.skipped_filter self.execute(pipeline, done_queue) while True: try: inst = done_queue.get_nowait() except queue.Empty: break else: inst.metrics.update(self.instances[inst.name].metrics) inst.metrics["handler_time"] = inst.execution_time inst.metrics["unrecognized"] = [] self.instances[inst.name] = inst print("") retry_errors = False if self.results.error and self.options.retry_build_errors: retry_errors = True retries = retries - 1 if retries == 0 or ( self.results.failed == 0 and not retry_errors): break self.show_brief() def update_counting_before_pipeline(self): ''' Updating counting before pipeline is necessary because statically filterd test instance never enter the pipeline. While some pipeline output needs the static filter stats. So need to prepare them before pipline starts. ''' for instance in self.instances.values(): if instance.status == TwisterStatus.FILTER and not instance.reason == 'runtime filter': self.results.skipped_filter += 1 self.results.skipped_configs += 1 self.results.skipped_cases += len(instance.testsuite.testcases) self.results.cases += len(instance.testsuite.testcases) elif instance.status == TwisterStatus.ERROR: self.results.error += 1 def show_brief(self): logger.info("%d test scenarios (%d test instances) selected, " "%d configurations skipped (%d by static filter, %d at runtime)." % (len(self.suites), len(self.instances), self.results.skipped_configs, self.results.skipped_filter, self.results.skipped_configs - self.results.skipped_filter)) def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False, retry_build_errors=False): for instance in self.instances.values(): if build_only: instance.run = False no_retry_statuses = [TwisterStatus.PASS, TwisterStatus.SKIP, TwisterStatus.FILTER] if not retry_build_errors: no_retry_statuses.append(TwisterStatus.ERROR) if instance.status not in no_retry_statuses: logger.debug(f"adding {instance.name}") if instance.status != TwisterStatus.NONE: instance.retries += 1 instance.status = TwisterStatus.NONE # Check if cmake package_helper script can be run in advance. instance.filter_stages = [] if instance.testsuite.filter: instance.filter_stages = self.get_cmake_filter_stages(instance.testsuite.filter, expr_parser.reserved.keys()) if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) elif instance.filter_stages and "full" not in instance.filter_stages: pipeline.put({"op": "filter", "test": instance}) else: cache_file = os.path.join(instance.build_dir, "CMakeCache.txt") if os.path.exists(cache_file) and self.env.options.aggressive_no_clean: pipeline.put({"op": "build", "test": instance}) else: pipeline.put({"op": "cmake", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): try: if sys.platform == 'linux': with self.jobserver.get_job(): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: instance = task['test'] pb = ProjectBuilder(instance, self.env, self.jobserver) pb.duts = self.duts pb.process(pipeline, done_queue, task, lock, results) return True else: while True: try: task = pipeline.get_nowait() except queue.Empty: break else: instance = task['test'] pb = ProjectBuilder(instance, self.env, self.jobserver) pb.duts = self.duts pb.process(pipeline, done_queue, task, lock, results) return True except Exception as e: logger.error(f"General exception: {e}") sys.exit(1) def execute(self, pipeline, done): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.options.build_only, self.options.test_only, retry_build_errors=self.options.retry_build_errors) logger.info("Added initial list of jobs to queue") processes = [] for _ in range(self.jobs): p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, self.results, )) processes.append(p) p.start() logger.debug(f"Launched {self.jobs} jobs") try: for p in processes: p.join() if p.exitcode != 0: logger.error(f"Process {p.pid} failed, aborting execution") for proc in processes: proc.terminate() sys.exit(1) except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() @staticmethod def get_cmake_filter_stages(filt, logic_keys): """ Analyze filter expressions from test yaml and decide if dts and/or kconfig based filtering will be needed.""" dts_required = False kconfig_required = False full_required = False filter_stages = [] # Compress args in expressions like "function('x', 'y')" so they are not split when splitting by whitespaces filt = filt.replace(", ", ",") # Remove logic words for k in logic_keys: filt = filt.replace(f"{k} ", "") # Remove brackets filt = filt.replace("(", "") filt = filt.replace(")", "") # Splite by whitespaces filt = filt.split() for expression in filt: if expression.startswith("dt_"): dts_required = True elif expression.startswith("CONFIG"): kconfig_required = True else: full_required = True if full_required: return ["full"] if dts_required: filter_stages.append("dts") if kconfig_required: filter_stages.append("kconfig") return filter_stages ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/runner.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
11,581
```python # vim: set syntax=python ts=4 : # import colorama import logging import os import shutil import sys import time from colorama import Fore from twisterlib.statuses import TwisterStatus from twisterlib.testplan import TestPlan from twisterlib.reports import Reporting from twisterlib.hardwaremap import HardwareMap from twisterlib.coverage import run_coverage from twisterlib.runner import TwisterRunner from twisterlib.environment import TwisterEnv from twisterlib.package import Artifacts logger = logging.getLogger("twister") logger.setLevel(logging.DEBUG) def setup_logging(outdir, log_file, verbose, timestamps): # create file handler which logs even debug messages if log_file: fh = logging.FileHandler(log_file) else: fh = logging.FileHandler(os.path.join(outdir, "twister.log")) fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() if verbose > 1: ch.setLevel(logging.DEBUG) else: ch.setLevel(logging.INFO) # create formatter and add it to the handlers if timestamps: formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") else: formatter = logging.Formatter("%(levelname)-7s - %(message)s") formatter_file = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) ch.setFormatter(formatter) fh.setFormatter(formatter_file) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) def init_color(colorama_strip): colorama.init(strip=colorama_strip) def main(options, default_options): start_time = time.time() # Configure color output color_strip = False if options.force_color else None colorama.init(strip=color_strip) init_color(colorama_strip=color_strip) previous_results = None # Cleanup if options.no_clean or options.only_failed or options.test_only or options.report_summary is not None: if os.path.exists(options.outdir): print("Keeping artifacts untouched") elif options.last_metrics: ls = os.path.join(options.outdir, "twister.json") if os.path.exists(ls): with open(ls, "r") as fp: previous_results = fp.read() else: sys.exit(f"Can't compare metrics with non existing file {ls}") elif os.path.exists(options.outdir): if options.clobber_output: print("Deleting output directory {}".format(options.outdir)) shutil.rmtree(options.outdir) else: for i in range(1, 100): new_out = options.outdir + ".{}".format(i) if not os.path.exists(new_out): print("Renaming output directory to {}".format(new_out)) shutil.move(options.outdir, new_out) break else: sys.exit(f"Too many '{options.outdir}.*' directories. Run either with --no-clean, " "or --clobber-output, or delete these directories manually.") previous_results_file = None os.makedirs(options.outdir, exist_ok=True) if options.last_metrics and previous_results: previous_results_file = os.path.join(options.outdir, "baseline.json") with open(previous_results_file, "w") as fp: fp.write(previous_results) VERBOSE = options.verbose setup_logging(options.outdir, options.log_file, VERBOSE, options.timestamps) env = TwisterEnv(options, default_options) env.discover() hwm = HardwareMap(env) ret = hwm.discover() if ret == 0: return 0 env.hwm = hwm tplan = TestPlan(env) try: tplan.discover() except RuntimeError as e: logger.error(f"{e}") return 1 if tplan.report() == 0: return 0 try: tplan.load() except RuntimeError as e: logger.error(f"{e}") return 1 if VERBOSE > 1: # if we are using command line platform filter, no need to list every # other platform as excluded, we know that already. # Show only the discards that apply to the selected platforms on the # command line for i in tplan.instances.values(): if i.status == TwisterStatus.FILTER: if options.platform and i.platform.name not in options.platform: continue logger.debug( "{:<25} {:<50} {}SKIPPED{}: {}".format( i.platform.name, i.testsuite.name, Fore.YELLOW, Fore.RESET, i.reason, ) ) report = Reporting(tplan, env) plan_file = os.path.join(options.outdir, "testplan.json") if not os.path.exists(plan_file): report.json_report(plan_file) if options.save_tests: report.json_report(options.save_tests) return 0 if options.report_summary is not None: if options.report_summary < 0: logger.error("The report summary value cannot be less than 0") return 1 report.synopsis() return 0 if options.device_testing and not options.build_only: print("\nDevice testing on:") hwm.dump(filtered=tplan.selected_platforms) print("") if options.dry_run: duration = time.time() - start_time logger.info("Completed in %d seconds" % (duration)) return 0 if options.short_build_path: tplan.create_build_dir_links() runner = TwisterRunner(tplan.instances, tplan.testsuites, env) runner.duts = hwm.duts runner.run() # figure out which report to use for size comparison report_to_use = None if options.compare_report: report_to_use = options.compare_report elif options.last_metrics: report_to_use = previous_results_file report.footprint_reports( report_to_use, options.show_footprint, options.all_deltas, options.footprint_threshold, options.last_metrics, ) duration = time.time() - start_time if VERBOSE > 1: runner.results.summary() report.summary(runner.results, options.disable_unrecognized_section_test, duration) coverage_completed = True if options.coverage: if not options.build_only: coverage_completed = run_coverage(tplan, options) else: logger.info("Skipping coverage report generation due to --build-only.") if options.device_testing and not options.build_only: hwm.summary(tplan.selected_platforms) report.save_reports( options.report_name, options.report_suffix, options.report_dir, options.no_update, options.platform_reports, ) report.synopsis() if options.package_artifacts: artifacts = Artifacts(env) artifacts.package() logger.info("Run completed") if ( runner.results.failed or runner.results.error or (tplan.warnings and options.warnings_as_errors) or (options.coverage and not coverage_completed) ): return 1 return 0 ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/twister_main.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,544
```python from __future__ import annotations from asyncio.log import logger from enum import Enum import platform import re import os import sys import subprocess import shlex from collections import OrderedDict import xml.etree.ElementTree as ET import logging import threading import time import shutil import json from pytest import ExitCode from twisterlib.reports import ReportStatus from twisterlib.error import ConfigurationError from twisterlib.environment import ZEPHYR_BASE, PYTEST_PLUGIN_INSTALLED from twisterlib.handlers import Handler, terminate_process, SUPPORTED_SIMS_IN_PYTEST from twisterlib.statuses import TwisterStatus from twisterlib.testinstance import TestInstance logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) _WINDOWS = platform.system() == 'Windows' result_re = re.compile(r".*(PASS|FAIL|SKIP) - (test_)?(\S*) in (\d*[.,]?\d*) seconds") class Harness: GCOV_START = "GCOV_COVERAGE_DUMP_START" GCOV_END = "GCOV_COVERAGE_DUMP_END" FAULT = "ZEPHYR FATAL ERROR" RUN_PASSED = "PROJECT EXECUTION SUCCESSFUL" RUN_FAILED = "PROJECT EXECUTION FAILED" run_id_pattern = r"RunID: (?P<run_id>.*)" def __init__(self): self._status = TwisterStatus.NONE self.reason = None self.type = None self.regex = [] self.matches = OrderedDict() self.ordered = True self.id = None self.fail_on_fault = True self.fault = False self.capture_coverage = False self.next_pattern = 0 self.record = None self.record_pattern = None self.record_as_json = None self.recording = [] self.ztest = False self.detected_suite_names = [] self.run_id = None self.matched_run_id = False self.run_id_exists = False self.instance: TestInstance | None = None self.testcase_output = "" self._match = False @property def status(self) -> TwisterStatus: return self._status @status.setter def status(self, value : TwisterStatus) -> None: # Check for illegal assignments by value try: key = value.name if isinstance(value, Enum) else value self._status = TwisterStatus[key] except KeyError: logger.error(f'Harness assigned status "{value}"' f' without an equivalent in TwisterStatus.' f' Assignment was ignored.') def configure(self, instance): self.instance = instance config = instance.testsuite.harness_config self.id = instance.testsuite.id self.run_id = instance.run_id if instance.testsuite.ignore_faults: self.fail_on_fault = False if config: self.type = config.get('type', None) self.regex = config.get('regex', []) self.ordered = config.get('ordered', True) self.record = config.get('record', {}) if self.record: self.record_pattern = re.compile(self.record.get("regex", "")) self.record_as_json = self.record.get("as_json") def build(self): pass def get_testcase_name(self): """ Get current TestCase name. """ return self.id def translate_record(self, record: dict) -> dict: if self.record_as_json: for k in self.record_as_json: if not k in record: continue try: record[k] = json.loads(record[k]) if record[k] else {} except json.JSONDecodeError as parse_error: logger.warning(f"HARNESS:{self.__class__.__name__}: recording JSON failed:" f" {parse_error} for '{k}':'{record[k]}'") # Don't set the Harness state to failed for recordings. record[k] = { 'ERROR': { 'msg': str(parse_error), 'doc': record[k] } } return record def parse_record(self, line) -> re.Match: match = None if self.record_pattern: match = self.record_pattern.search(line) if match: rec = self.translate_record({ k:v.strip() for k,v in match.groupdict(default="").items() }) self.recording.append(rec) return match # def process_test(self, line): self.parse_record(line) runid_match = re.search(self.run_id_pattern, line) if runid_match: run_id = runid_match.group("run_id") self.run_id_exists = True if run_id == str(self.run_id): self.matched_run_id = True if self.RUN_PASSED in line: if self.fault: self.status = TwisterStatus.FAIL self.reason = "Fault detected while running test" else: self.status = TwisterStatus.PASS if self.RUN_FAILED in line: self.status = TwisterStatus.FAIL self.reason = "Testsuite failed" if self.fail_on_fault: if self.FAULT == line: self.fault = True if self.GCOV_START in line: self.capture_coverage = True elif self.GCOV_END in line: self.capture_coverage = False class Robot(Harness): is_robot_test = True def configure(self, instance): super(Robot, self).configure(instance) self.instance = instance config = instance.testsuite.harness_config if config: self.path = config.get('robot_testsuite', None) self.option = config.get('robot_option', None) def handle(self, line): ''' Test cases that make use of this harness care about results given by Robot Framework which is called in run_robot_test(), so works of this handle is trying to give a PASS or FAIL to avoid timeout, nothing is writen into handler.log ''' self.instance.status = TwisterStatus.PASS tc = self.instance.get_case_or_create(self.id) tc.status = TwisterStatus.PASS def run_robot_test(self, command, handler): start_time = time.time() env = os.environ.copy() if self.option: if isinstance(self.option, list): for option in self.option: for v in str(option).split(): command.append(f'{v}') else: for v in str(self.option).split(): command.append(f'{v}') if self.path is None: raise PytestHarnessException(f'The parameter robot_testsuite is mandatory') if isinstance(self.path, list): for suite in self.path: command.append(os.path.join(handler.sourcedir, suite)) else: command.append(os.path.join(handler.sourcedir, self.path)) with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.instance.build_dir, env=env) as renode_test_proc: out, _ = renode_test_proc.communicate() self.instance.execution_time = time.time() - start_time if renode_test_proc.returncode == 0: self.instance.status = TwisterStatus.PASS # all tests in one Robot file are treated as a single test case, # so its status should be set accordingly to the instance status # please note that there should be only one testcase in testcases list self.instance.testcases[0].status = TwisterStatus.PASS else: logger.error("Robot test failure: %s for %s" % (handler.sourcedir, self.instance.platform.name)) self.instance.status = TwisterStatus.FAIL self.instance.testcases[0].status = TwisterStatus.FAIL if out: with open(os.path.join(self.instance.build_dir, handler.log), "wt") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) class Console(Harness): def get_testcase_name(self): ''' Get current TestCase name. Console Harness id has only TestSuite id without TestCase name suffix. Only the first TestCase name might be taken if available when a Ztest with a single test case is configured to use this harness type for simplified output parsing instead of the Ztest harness as Ztest suite should do. ''' if self.instance and len(self.instance.testcases) == 1: return self.instance.testcases[0].name return super(Console, self).get_testcase_name() def configure(self, instance): super(Console, self).configure(instance) if self.regex is None or len(self.regex) == 0: self.status = TwisterStatus.FAIL tc = self.instance.set_case_status_by_name( self.get_testcase_name(), TwisterStatus.FAIL, f"HARNESS:{self.__class__.__name__}:no regex patterns configured." ) raise ConfigurationError(self.instance.name, tc.reason) if self.type == "one_line": self.pattern = re.compile(self.regex[0]) self.patterns_expected = 1 elif self.type == "multi_line": self.patterns = [] for r in self.regex: self.patterns.append(re.compile(r)) self.patterns_expected = len(self.patterns) else: self.status = TwisterStatus.FAIL tc = self.instance.set_case_status_by_name( self.get_testcase_name(), TwisterStatus.FAIL, f"HARNESS:{self.__class__.__name__}:incorrect type={self.type}" ) raise ConfigurationError(self.instance.name, tc.reason) # def handle(self, line): if self.type == "one_line": if self.pattern.search(line): logger.debug(f"HARNESS:{self.__class__.__name__}:EXPECTED:" f"'{self.pattern.pattern}'") self.next_pattern += 1 self.status = TwisterStatus.PASS elif self.type == "multi_line" and self.ordered: if (self.next_pattern < len(self.patterns) and self.patterns[self.next_pattern].search(line)): logger.debug(f"HARNESS:{self.__class__.__name__}:EXPECTED(" f"{self.next_pattern + 1}/{self.patterns_expected}):" f"'{self.patterns[self.next_pattern].pattern}'") self.next_pattern += 1 if self.next_pattern >= len(self.patterns): self.status = TwisterStatus.PASS elif self.type == "multi_line" and not self.ordered: for i, pattern in enumerate(self.patterns): r = self.regex[i] if pattern.search(line) and not r in self.matches: self.matches[r] = line logger.debug(f"HARNESS:{self.__class__.__name__}:EXPECTED(" f"{len(self.matches)}/{self.patterns_expected}):" f"'{pattern.pattern}'") if len(self.matches) == len(self.regex): self.status = TwisterStatus.PASS else: logger.error("Unknown harness_config type") if self.fail_on_fault: if self.FAULT in line: self.fault = True if self.GCOV_START in line: self.capture_coverage = True elif self.GCOV_END in line: self.capture_coverage = False self.process_test(line) # Reset the resulting test state to FAIL when not all of the patterns were # found in the output, but just ztest's 'PROJECT EXECUTION SUCCESSFUL'. # It might happen because of the pattern sequence diverged from the # test code, the test platform has console issues, or even some other # test image was executed. # TODO: Introduce explicit match policy type to reject # unexpected console output, allow missing patterns, deny duplicates. if self.status == TwisterStatus.PASS and \ self.ordered and \ self.next_pattern < self.patterns_expected: logger.error(f"HARNESS:{self.__class__.__name__}: failed with" f" {self.next_pattern} of {self.patterns_expected}" f" expected ordered patterns.") self.status = TwisterStatus.FAIL self.reason = "patterns did not match (ordered)" if self.status == TwisterStatus.PASS and \ not self.ordered and \ len(self.matches) < self.patterns_expected: logger.error(f"HARNESS:{self.__class__.__name__}: failed with" f" {len(self.matches)} of {self.patterns_expected}" f" expected unordered patterns.") self.status = TwisterStatus.FAIL self.reason = "patterns did not match (unordered)" tc = self.instance.get_case_or_create(self.get_testcase_name()) if self.status == TwisterStatus.PASS: tc.status = TwisterStatus.PASS else: tc.status = TwisterStatus.FAIL class PytestHarnessException(Exception): """General exception for pytest.""" class Pytest(Harness): def configure(self, instance: TestInstance): super(Pytest, self).configure(instance) self.running_dir = instance.build_dir self.source_dir = instance.testsuite.source_dir self.report_file = os.path.join(self.running_dir, 'report.xml') self.pytest_log_file_path = os.path.join(self.running_dir, 'twister_harness.log') self.reserved_dut = None self._output = [] def pytest_run(self, timeout): try: cmd = self.generate_command() self.run_command(cmd, timeout) except PytestHarnessException as pytest_exception: logger.error(str(pytest_exception)) self.status = TwisterStatus.FAIL self.instance.reason = str(pytest_exception) finally: self.instance.record(self.recording) self._update_test_status() if self.reserved_dut: self.instance.handler.make_dut_available(self.reserved_dut) def generate_command(self): config = self.instance.testsuite.harness_config handler: Handler = self.instance.handler pytest_root = config.get('pytest_root', ['pytest']) if config else ['pytest'] pytest_args_yaml = config.get('pytest_args', []) if config else [] pytest_dut_scope = config.get('pytest_dut_scope', None) if config else None command = [ 'pytest', '--twister-harness', '-s', '-v', f'--build-dir={self.running_dir}', f'--junit-xml={self.report_file}', '--log-file-level=DEBUG', '--log-file-format=%(asctime)s.%(msecs)d:%(levelname)s:%(name)s: %(message)s', f'--log-file={self.pytest_log_file_path}', f'--platform={self.instance.platform.name}' ] command.extend([os.path.normpath(os.path.join( self.source_dir, os.path.expanduser(os.path.expandvars(src)))) for src in pytest_root]) if pytest_dut_scope: command.append(f'--dut-scope={pytest_dut_scope}') # Always pass output from the pytest test and the test image up to Twister log. command.extend([ '--log-cli-level=DEBUG', '--log-cli-format=%(levelname)s: %(message)s' ]) # Use the test timeout as the base timeout for pytest base_timeout = handler.get_test_timeout() command.append(f'--base-timeout={base_timeout}') if handler.type_str == 'device': command.extend( self._generate_parameters_for_hardware(handler) ) elif handler.type_str in SUPPORTED_SIMS_IN_PYTEST: command.append(f'--device-type={handler.type_str}') elif handler.type_str == 'build': command.append('--device-type=custom') else: raise PytestHarnessException(f'Support for handler {handler.type_str} not implemented yet') if handler.type_str != 'device': for fixture in handler.options.fixture: command.append(f'--twister-fixture={fixture}') if handler.options.pytest_args: command.extend(handler.options.pytest_args) command.extend(pytest_args_yaml) return command def _generate_parameters_for_hardware(self, handler: Handler): command = ['--device-type=hardware'] hardware = handler.get_hardware() if not hardware: raise PytestHarnessException('Hardware is not available') # update the instance with the device id to have it in the summary report self.instance.dut = hardware.id self.reserved_dut = hardware if hardware.serial_pty: command.append(f'--device-serial-pty={hardware.serial_pty}') else: command.extend([ f'--device-serial={hardware.serial}', f'--device-serial-baud={hardware.baud}' ]) options = handler.options if runner := hardware.runner or options.west_runner: command.append(f'--runner={runner}') if hardware.runner_params: for param in hardware.runner_params: command.append(f'--runner-params={param}') if options.west_flash and options.west_flash != []: command.append(f'--west-flash-extra-args={options.west_flash}') if board_id := hardware.probe_id or hardware.id: command.append(f'--device-id={board_id}') if hardware.product: command.append(f'--device-product={hardware.product}') if hardware.pre_script: command.append(f'--pre-script={hardware.pre_script}') if hardware.post_flash_script: command.append(f'--post-flash-script={hardware.post_flash_script}') if hardware.post_script: command.append(f'--post-script={hardware.post_script}') if hardware.flash_before: command.append(f'--flash-before={hardware.flash_before}') for fixture in hardware.fixtures: command.append(f'--twister-fixture={fixture}') return command def run_command(self, cmd, timeout): cmd, env = self._update_command_with_env_dependencies(cmd) with subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env ) as proc: try: reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(timeout) if reader_t.is_alive(): terminate_process(proc) logger.warning('Timeout has occurred. Can be extended in testspec file. ' f'Currently set to {timeout} seconds.') self.instance.reason = 'Pytest timeout' self.status = TwisterStatus.FAIL proc.wait(timeout) except subprocess.TimeoutExpired: self.status = TwisterStatus.FAIL proc.kill() if proc.returncode in (ExitCode.INTERRUPTED, ExitCode.USAGE_ERROR, ExitCode.INTERNAL_ERROR): self.status = TwisterStatus.ERROR self.instance.reason = f'Pytest error - return code {proc.returncode}' with open(self.pytest_log_file_path, 'w') as log_file: log_file.write(shlex.join(cmd) + '\n\n') log_file.write('\n'.join(self._output)) @staticmethod def _update_command_with_env_dependencies(cmd): ''' If python plugin wasn't installed by pip, then try to indicate it to pytest by update PYTHONPATH and append -p argument to pytest command. ''' env = os.environ.copy() if not PYTEST_PLUGIN_INSTALLED: cmd.extend(['-p', 'twister_harness.plugin']) pytest_plugin_path = os.path.join(ZEPHYR_BASE, 'scripts', 'pylib', 'pytest-twister-harness', 'src') env['PYTHONPATH'] = pytest_plugin_path + os.pathsep + env.get('PYTHONPATH', '') if _WINDOWS: cmd_append_python_path = f'set PYTHONPATH={pytest_plugin_path};%PYTHONPATH% && ' else: cmd_append_python_path = f'export PYTHONPATH={pytest_plugin_path}:${{PYTHONPATH}} && ' else: cmd_append_python_path = '' cmd_to_print = cmd_append_python_path + shlex.join(cmd) logger.debug('Running pytest command: %s', cmd_to_print) return cmd, env def _output_reader(self, proc): self._output = [] while proc.stdout.readable() and proc.poll() is None: line = proc.stdout.readline().decode().strip() if not line: continue self._output.append(line) logger.debug('PYTEST: %s', line) self.parse_record(line) proc.communicate() def _update_test_status(self): if self.status == TwisterStatus.NONE: self.instance.testcases = [] try: self._parse_report_file(self.report_file) except Exception as e: logger.error(f'Error when parsing file {self.report_file}: {e}') self.status = TwisterStatus.FAIL finally: if not self.instance.testcases: self.instance.init_cases() self.instance.status = self.status if self.status != TwisterStatus.NONE else \ TwisterStatus.FAIL if self.instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: self.instance.reason = self.instance.reason or 'Pytest failed' self.instance.add_missing_case_status(TwisterStatus.BLOCK, self.instance.reason) def _parse_report_file(self, report): tree = ET.parse(report) root = tree.getroot() if elem_ts := root.find('testsuite'): if elem_ts.get('failures') != '0': self.status = TwisterStatus.FAIL self.instance.reason = f"{elem_ts.get('failures')}/{elem_ts.get('tests')} pytest scenario(s) failed" elif elem_ts.get('errors') != '0': self.status = TwisterStatus.ERROR self.instance.reason = 'Error during pytest execution' elif elem_ts.get('skipped') == elem_ts.get('tests'): self.status = TwisterStatus.SKIP else: self.status = TwisterStatus.PASS self.instance.execution_time = float(elem_ts.get('time')) for elem_tc in elem_ts.findall('testcase'): tc = self.instance.add_testcase(f"{self.id}.{elem_tc.get('name')}") tc.duration = float(elem_tc.get('time')) elem = elem_tc.find('*') if elem is None: tc.status = TwisterStatus.PASS else: if elem.tag == ReportStatus.SKIP: tc.status = TwisterStatus.SKIP elif elem.tag == ReportStatus.FAIL: tc.status = TwisterStatus.FAIL else: tc.status = TwisterStatus.ERROR tc.reason = elem.get('message') tc.output = elem.text else: self.status = TwisterStatus.SKIP self.instance.reason = 'No tests collected' class Gtest(Harness): ANSI_ESCAPE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') TEST_START_PATTERN = r".*\[ RUN \] (?P<suite_name>[a-zA-Z_][a-zA-Z0-9_]*)\.(?P<test_name>[a-zA-Z_][a-zA-Z0-9_]*)" TEST_PASS_PATTERN = r".*\[ OK \] (?P<suite_name>[a-zA-Z_][a-zA-Z0-9_]*)\.(?P<test_name>[a-zA-Z_][a-zA-Z0-9_]*)" TEST_SKIP_PATTERN = r".*\[ DISABLED \] (?P<suite_name>[a-zA-Z_][a-zA-Z0-9_]*)\.(?P<test_name>[a-zA-Z_][a-zA-Z0-9_]*)" TEST_FAIL_PATTERN = r".*\[ FAILED \] (?P<suite_name>[a-zA-Z_][a-zA-Z0-9_]*)\.(?P<test_name>[a-zA-Z_][a-zA-Z0-9_]*)" FINISHED_PATTERN = r".*\[==========\] Done running all tests\." def __init__(self): super().__init__() self.tc = None self.has_failures = False def handle(self, line): # Strip the ANSI characters, they mess up the patterns non_ansi_line = self.ANSI_ESCAPE.sub('', line) if self.status != TwisterStatus.NONE: return # Check if we started running a new test test_start_match = re.search(self.TEST_START_PATTERN, non_ansi_line) if test_start_match: # Add the suite name suite_name = test_start_match.group("suite_name") if suite_name not in self.detected_suite_names: self.detected_suite_names.append(suite_name) # Generate the internal name of the test name = "{}.{}.{}".format(self.id, suite_name, test_start_match.group("test_name")) # Assert that we don't already have a running test assert ( self.tc is None ), "gTest error, {} didn't finish".format(self.tc) # Check that the instance doesn't exist yet (prevents re-running) tc = self.instance.get_case_by_name(name) assert tc is None, "gTest error, {} running twice".format(tc) # Create the test instance and set the context tc = self.instance.get_case_or_create(name) self.tc = tc self.tc.status = TwisterStatus.STARTED self.testcase_output += line + "\n" self._match = True # Check if the test run finished finished_match = re.search(self.FINISHED_PATTERN, non_ansi_line) if finished_match: tc = self.instance.get_case_or_create(self.id) if self.has_failures or self.tc is not None: self.status = TwisterStatus.FAIL tc.status = TwisterStatus.FAIL else: self.status = TwisterStatus.PASS tc.status = TwisterStatus.PASS return # Check if the individual test finished state, name = self._check_result(non_ansi_line) if state == TwisterStatus.NONE or name is None: # Nothing finished, keep processing lines return # Get the matching test and make sure it's the same as the current context tc = self.instance.get_case_by_name(name) assert ( tc is not None and tc == self.tc ), "gTest error, mismatched tests. Expected {} but got {}".format(self.tc, tc) # Test finished, clear the context self.tc = None # Update the status of the test tc.status = state if tc.status == TwisterStatus.FAIL: self.has_failures = True tc.output = self.testcase_output self.testcase_output = "" self._match = False def _check_result(self, line): test_pass_match = re.search(self.TEST_PASS_PATTERN, line) if test_pass_match: return TwisterStatus.PASS, \ "{}.{}.{}".format( self.id, test_pass_match.group("suite_name"), test_pass_match.group("test_name") ) test_skip_match = re.search(self.TEST_SKIP_PATTERN, line) if test_skip_match: return TwisterStatus.SKIP, \ "{}.{}.{}".format( self.id, test_skip_match.group("suite_name"), test_skip_match.group("test_name") ) test_fail_match = re.search(self.TEST_FAIL_PATTERN, line) if test_fail_match: return TwisterStatus.FAIL, \ "{}.{}.{}".format( self.id, test_fail_match.group("suite_name"), test_fail_match.group("test_name") ) return None, None class Test(Harness): __test__ = False # for pytest to skip this class when collects tests RUN_PASSED = "PROJECT EXECUTION SUCCESSFUL" RUN_FAILED = "PROJECT EXECUTION FAILED" test_suite_start_pattern = r"Running TESTSUITE (?P<suite_name>.*)" ZTEST_START_PATTERN = r"START - (test_)?([a-zA-Z0-9_-]+)" def handle(self, line): test_suite_match = re.search(self.test_suite_start_pattern, line) if test_suite_match: suite_name = test_suite_match.group("suite_name") self.detected_suite_names.append(suite_name) testcase_match = re.search(self.ZTEST_START_PATTERN, line) if testcase_match: name = "{}.{}".format(self.id, testcase_match.group(2)) tc = self.instance.get_case_or_create(name) # Mark the test as started, if something happens here, it is mostly # due to this tests, for example timeout. This should in this case # be marked as failed and not blocked (not run). tc.status = TwisterStatus.STARTED if testcase_match or self._match: self.testcase_output += line + "\n" self._match = True result_match = result_re.match(line) # some testcases are skipped based on predicates and do not show up # during test execution, however they are listed in the summary. Parse # the summary for status and use that status instead. summary_re = re.compile(r"- (PASS|FAIL|SKIP) - \[([^\.]*).(test_)?(\S*)\] duration = (\d*[.,]?\d*) seconds") summary_match = summary_re.match(line) if result_match: matched_status = result_match.group(1) name = "{}.{}".format(self.id, result_match.group(3)) tc = self.instance.get_case_or_create(name) tc.status = TwisterStatus[matched_status] if tc.status == TwisterStatus.SKIP: tc.reason = "ztest skip" tc.duration = float(result_match.group(4)) if tc.status == TwisterStatus.FAIL: tc.output = self.testcase_output self.testcase_output = "" self._match = False self.ztest = True elif summary_match: matched_status = summary_match.group(1) self.detected_suite_names.append(summary_match.group(2)) name = "{}.{}".format(self.id, summary_match.group(4)) tc = self.instance.get_case_or_create(name) tc.status = TwisterStatus[matched_status] if tc.status == TwisterStatus.SKIP: tc.reason = "ztest skip" tc.duration = float(summary_match.group(5)) if tc.status == TwisterStatus.FAIL: tc.output = self.testcase_output self.testcase_output = "" self._match = False self.ztest = True self.process_test(line) if not self.ztest and self.status != TwisterStatus.NONE: logger.debug(f"not a ztest and no state for {self.id}") tc = self.instance.get_case_or_create(self.id) if self.status == TwisterStatus.PASS: tc.status = TwisterStatus.PASS else: tc.status = TwisterStatus.FAIL tc.reason = "Test failure" class Ztest(Test): pass class Bsim(Harness): def build(self): """ Copying the application executable to BabbleSim's bin directory enables running multidevice bsim tests after twister has built them. """ if self.instance is None: return original_exe_path: str = os.path.join(self.instance.build_dir, 'zephyr', 'zephyr.exe') if not os.path.exists(original_exe_path): logger.warning('Cannot copy bsim exe - cannot find original executable.') return bsim_out_path: str = os.getenv('BSIM_OUT_PATH', '') if not bsim_out_path: logger.warning('Cannot copy bsim exe - BSIM_OUT_PATH not provided.') return new_exe_name: str = self.instance.testsuite.harness_config.get('bsim_exe_name', '') if new_exe_name: new_exe_name = f'bs_{self.instance.platform.name}_{new_exe_name}' else: new_exe_name = self.instance.name new_exe_name = f'bs_{new_exe_name}' new_exe_name = new_exe_name.replace(os.path.sep, '_').replace('.', '_').replace('@', '_') new_exe_path: str = os.path.join(bsim_out_path, 'bin', new_exe_name) logger.debug(f'Copying executable from {original_exe_path} to {new_exe_path}') shutil.copy(original_exe_path, new_exe_path) class HarnessImporter: @staticmethod def get_harness(harness_name): thismodule = sys.modules[__name__] try: if harness_name: harness_class = getattr(thismodule, harness_name) else: harness_class = getattr(thismodule, 'Test') return harness_class() except AttributeError as e: logger.debug(f"harness {harness_name} not implemented: {e}") return None ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/harness.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
7,113
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import re from collections import OrderedDict class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # path_to_url val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/cmakecache.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,226
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import argparse import json import logging import os import re import shutil import subprocess import sys from datetime import datetime, timezone from importlib import metadata from pathlib import Path from typing import Generator, List from twisterlib.coverage import supported_coverage_formats logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) from twisterlib.error import TwisterRuntimeError from twisterlib.log_helper import log_command ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import zephyr_module # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) def _get_installed_packages() -> Generator[str, None, None]: """Return list of installed python packages.""" for dist in metadata.distributions(): yield dist.metadata['Name'] installed_packages: List[str] = list(_get_installed_packages()) PYTEST_PLUGIN_INSTALLED = 'pytest-twister-harness' in installed_packages def norm_path(astring): newstring = os.path.normpath(astring).replace(os.sep, '/') return newstring def add_parse_arguments(parser = None): if parser is None: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) parser.fromfile_prefix_chars = "+" case_select = parser.add_argument_group("Test case selection", """ Artificially long but functional example: $ ./scripts/twister -v \\ --testsuite-root tests/ztest/base \\ --testsuite-root tests/kernel \\ --test tests/ztest/base/testing.ztest.verbose_0 \\ --test tests/kernel/fifo/fifo_api/kernel.fifo "kernel.fifo.poll" is one of the test section names in __/fifo_api/testcase.yaml """) platform_group_option = parser.add_mutually_exclusive_group() run_group_option = parser.add_mutually_exclusive_group() device = parser.add_mutually_exclusive_group() test_or_build = parser.add_mutually_exclusive_group() test_xor_subtest = case_select.add_mutually_exclusive_group() test_xor_generator = case_select.add_mutually_exclusive_group() valgrind_asan_group = parser.add_mutually_exclusive_group() footprint_group = parser.add_argument_group( title="Memory footprint", description="Collect and report ROM/RAM size footprint for the test instance images built.") case_select.add_argument( "-E", "--save-tests", metavar="FILENAME", action="store", help="Write a list of tests and platforms to be run to file.") case_select.add_argument( "-F", "--load-tests", metavar="FILENAME", action="store", help="Load a list of tests and platforms to be run from file.") case_select.add_argument( "-T", "--testsuite-root", action="append", default=[], type = norm_path, help="Base directory to recursively search for test cases. All " "testcase.yaml files under here will be processed. May be " "called multiple times. Defaults to the 'samples/' and " "'tests/' directories at the base of the Zephyr tree.") case_select.add_argument( "-f", "--only-failed", action="store_true", help="Run only those tests that failed the previous twister run " "invocation.") case_select.add_argument("--list-tests", action="store_true", help="""List of all sub-test functions recursively found in all --testsuite-root arguments. Note different sub-tests can share the same section name and come from different directories. The output is flattened and reports --sub-test names only, not their directories. For instance net.socket.getaddrinfo_ok and net.socket.fd_set belong to different directories. """) case_select.add_argument("--test-tree", action="store_true", help="""Output the test plan in a tree form""") platform_group_option.add_argument( "-G", "--integration", action="store_true", help="Run integration tests") platform_group_option.add_argument( "--emulation-only", action="store_true", help="Only build and run emulation platforms") run_group_option.add_argument( "--device-testing", action="store_true", help="Test on device directly. Specify the serial device to " "use with the --device-serial option.") run_group_option.add_argument("--generate-hardware-map", help="""Probe serial devices connected to this platform and create a hardware map file to be used with --device-testing """) device.add_argument("--device-serial", help="""Serial device for accessing the board (e.g., /dev/ttyACM0) """) device.add_argument("--device-serial-pty", help="""Script for controlling pseudoterminal. Twister believes that it interacts with a terminal when it actually interacts with the script. E.g "twister --device-testing --device-serial-pty <script> """) device.add_argument("--hardware-map", help="""Load hardware map from a file. This will be used for testing on hardware that is listed in the file. """) parser.add_argument("--device-flash-timeout", type=int, default=60, help="""Set timeout for the device flash operation in seconds. """) parser.add_argument("--device-flash-with-test", action="store_true", help="""Add a test case timeout to the flash operation timeout when flash operation also executes test case on the platform. """) parser.add_argument("--flash-before", action="store_true", default=False, help="""Flash device before attaching to serial port. This is useful for devices that share the same port for programming and serial console, or use soft-USB, where flash must come first. """) test_or_build.add_argument( "-b", "--build-only", action="store_true", default="--prep-artifacts-for-testing" in sys.argv, help="Only build the code, do not attempt to run the code on targets.") test_or_build.add_argument( "--prep-artifacts-for-testing", action="store_true", help="Generate artifacts for testing, do not attempt to run the" "code on targets.") parser.add_argument( "--package-artifacts", help="Package artifacts needed for flashing in a file to be used with --test-only" ) test_or_build.add_argument( "--test-only", action="store_true", help="""Only run device tests with current artifacts, do not build the code""") parser.add_argument("--timeout-multiplier", type=float, default=1, help="""Globally adjust tests timeouts by specified multiplier. The resulting test timeout would be multiplication of test timeout value, board-level timeout multiplier and global timeout multiplier (this parameter)""") test_xor_subtest.add_argument( "-s", "--test", "--scenario", action="append", type = norm_path, help="Run only the specified testsuite scenario. These are named by " "<path/relative/to/Zephyr/base/section.name.in.testcase.yaml>") test_xor_subtest.add_argument( "--sub-test", action="append", help="""Recursively find sub-test functions and run the entire test section where they were found, including all sibling test functions. Sub-tests are named by: section.name.in.testcase.yaml.function_name_without_test_prefix Example: In kernel.fifo.fifo_loop: 'kernel.fifo' is a section name and 'fifo_loop' is a name of a function found in main.c without test prefix. """) parser.add_argument( "--pytest-args", action="append", help="""Pass additional arguments to the pytest subprocess. This parameter will extend the pytest_args from the harness_config in YAML file. """) valgrind_asan_group.add_argument( "--enable-valgrind", action="store_true", help="""Run binary through valgrind and check for several memory access errors. Valgrind needs to be installed on the host. This option only works with host binaries such as those generated for the native_sim configuration and is mutual exclusive with --enable-asan. """) valgrind_asan_group.add_argument( "--enable-asan", action="store_true", help="""Enable address sanitizer to check for several memory access errors. Libasan needs to be installed on the host. This option only works with host binaries such as those generated for the native_sim configuration and is mutual exclusive with --enable-valgrind. """) # Start of individual args place them in alpha-beta order board_root_list = ["%s/boards" % ZEPHYR_BASE, "%s/subsys/testsuite/boards" % ZEPHYR_BASE] modules = zephyr_module.parse_modules(ZEPHYR_BASE) for module in modules: board_root = module.meta.get("build", {}).get("settings", {}).get("board_root") if board_root: board_root_list.append(os.path.join(module.project, board_root, "boards")) parser.add_argument( "-A", "--board-root", action="append", default=board_root_list, help="""Directory to search for board configuration files. All .yaml files in the directory will be processed. The directory should have the same structure in the main Zephyr tree: boards/<vendor>/<board_name>/""") parser.add_argument( "--allow-installed-plugin", action="store_true", default=None, help="Allow to use pytest plugin installed by pip for pytest tests." ) parser.add_argument( "-a", "--arch", action="append", help="Arch filter for testing. Takes precedence over --platform. " "If unspecified, test all arches. Multiple invocations " "are treated as a logical 'or' relationship") parser.add_argument( "-B", "--subset", help="Only run a subset of the tests, 1/4 for running the first 25%%, " "3/5 means run the 3rd fifth of the total. " "This option is useful when running a large number of tests on " "different hosts to speed up execution time.") parser.add_argument( "--shuffle-tests", action="store_true", default=None, help="""Shuffle test execution order to get randomly distributed tests across subsets. Used only when --subset is provided.""") parser.add_argument( "--shuffle-tests-seed", action="store", default=None, help="""Seed value for random generator used to shuffle tests. If not provided, seed in generated by system. Used only when --shuffle-tests is provided.""") parser.add_argument("-C", "--coverage", action="store_true", help="Generate coverage reports. Implies " "--enable-coverage.") parser.add_argument( "-c", "--clobber-output", action="store_true", help="Cleaning the output directory will simply delete it instead " "of the default policy of renaming.") parser.add_argument( "--cmake-only", action="store_true", help="Only run cmake, do not build or run.") parser.add_argument("--coverage-basedir", default=ZEPHYR_BASE, help="Base source directory for coverage report.") parser.add_argument("--coverage-platform", action="append", default=[], help="Platforms to run coverage reports on. " "This option may be used multiple times. " "Default to what was selected with --platform.") parser.add_argument("--coverage-tool", choices=['lcov', 'gcovr'], default='gcovr', help="Tool to use to generate coverage report.") parser.add_argument("--coverage-formats", action="store", default=None, # default behavior is set in run_coverage help="Output formats to use for generated coverage reports, as a comma-separated list. " + "Valid options for 'gcovr' tool are: " + ','.join(supported_coverage_formats['gcovr']) + " (html - default)." + " Valid options for 'lcov' tool are: " + ','.join(supported_coverage_formats['lcov']) + " (html,lcov - default).") parser.add_argument("--test-config", action="store", default=os.path.join(ZEPHYR_BASE, "tests", "test_config.yaml"), help="Path to file with plans and test configurations.") parser.add_argument("--level", action="store", help="Test level to be used. By default, no levels are used for filtering" "and do the selection based on existing filters.") parser.add_argument( "--device-serial-baud", action="store", default=None, help="Serial device baud rate (default 115200)") parser.add_argument( "--disable-suite-name-check", action="store_true", default=False, help="Disable extended test suite name verification at the beginning " "of Ztest test. This option could be useful for tests or " "platforms, which from some reasons cannot print early logs.") parser.add_argument("-e", "--exclude-tag", action="append", help="Specify tags of tests that should not run. " "Default is to run all tests with all tags.") parser.add_argument("--enable-coverage", action="store_true", help="Enable code coverage using gcov.") parser.add_argument( "--enable-lsan", action="store_true", help="""Enable leak sanitizer to check for heap memory leaks. Libasan needs to be installed on the host. This option only works with host binaries such as those generated for the native_sim configuration and when --enable-asan is given. """) parser.add_argument( "--enable-ubsan", action="store_true", help="""Enable undefined behavior sanitizer to check for undefined behaviour during program execution. It uses an optional runtime library to provide better error diagnostics. This option only works with host binaries such as those generated for the native_sim configuration. """) parser.add_argument( "--filter", choices=['buildable', 'runnable'], default='buildable', help="""Filter tests to be built and executed. By default everything is built and if a test is runnable (emulation or a connected device), it is run. This option allows for example to only build tests that can actually be run. Runnable is a subset of buildable.""") parser.add_argument("--force-color", action="store_true", help="Always output ANSI color escape sequences " "even when the output is redirected (not a tty)") parser.add_argument("--force-toolchain", action="store_true", help="Do not filter based on toolchain, use the set " " toolchain unconditionally") parser.add_argument("--gcov-tool", type=Path, default=None, help="Path to the gcov tool to use for code coverage " "reports") footprint_group.add_argument( "--create-rom-ram-report", action="store_true", help="Generate detailed json reports with ROM/RAM symbol sizes for each test image built " "using additional build option `--target footprint`.") footprint_group.add_argument( "--footprint-report", nargs="?", default=None, choices=['all', 'ROM', 'RAM'], const="all", help="Select which memory area symbols' data to collect as 'footprint' property " "of each test suite built, and report in 'twister_footprint.json' together " "with the relevant execution metadata the same way as in `twister.json`. " "Implies '--create-rom-ram-report' to generate the footprint data files. " "No value means '%(const)s'. Default: %(default)s""") footprint_group.add_argument( "--enable-size-report", action="store_true", help="Collect and report ROM/RAM section sizes for each test image built.") parser.add_argument( "--disable-unrecognized-section-test", action="store_true", default=False, help="Don't error on unrecognized sections in the binary images.") footprint_group.add_argument( "--footprint-from-buildlog", action = "store_true", help="Take ROM/RAM sections footprint summary values from the 'build.log' " "instead of 'objdump' results used otherwise." "Requires --enable-size-report or one of the baseline comparison modes." "Warning: the feature will not work correctly with sysbuild.") compare_group_option = footprint_group.add_mutually_exclusive_group() compare_group_option.add_argument( "-m", "--last-metrics", action="store_true", help="Compare footprints to the previous twister invocation as a baseline " "running in the same output directory. " "Implies --enable-size-report option.") compare_group_option.add_argument( "--compare-report", help="Use this report file as a baseline for footprint comparison. " "The file should be of 'twister.json' schema. " "Implies --enable-size-report option.") footprint_group.add_argument( "--show-footprint", action="store_true", help="With footprint comparison to a baseline, log ROM/RAM section deltas. ") footprint_group.add_argument( "-H", "--footprint-threshold", type=float, default=5.0, help="With footprint comparison to a baseline, " "warn the user for any of the footprint metric change which is greater or equal " "to the specified percentage value. " "Default is %(default)s for %(default)s%% delta from the new footprint value. " "Use zero to warn on any footprint metric increase.") footprint_group.add_argument( "-D", "--all-deltas", action="store_true", help="With footprint comparison to a baseline, " "warn on any footprint change, increase or decrease. " "Implies --footprint-threshold=0") footprint_group.add_argument( "-z", "--size", action="append", metavar='FILENAME', help="Ignore all other command line options and just produce a report to " "stdout with ROM/RAM section sizes on the specified binary images.") parser.add_argument( "-i", "--inline-logs", action="store_true", help="Upon test failure, print relevant log data to stdout " "instead of just a path to it.") parser.add_argument("--ignore-platform-key", action="store_true", help="Do not filter based on platform key") parser.add_argument( "-j", "--jobs", type=int, help="Number of jobs for building, defaults to number of CPU threads, " "overcommitted by factor 2 when --build-only.") parser.add_argument( "-K", "--force-platform", action="store_true", help="""Force testing on selected platforms, even if they are excluded in the test configuration (testcase.yaml).""" ) parser.add_argument( "-l", "--all", action="store_true", help="Build/test on all platforms. Any --platform arguments " "ignored.") parser.add_argument("--list-tags", action="store_true", help="List all tags occurring in selected tests.") parser.add_argument("--log-file", metavar="FILENAME", action="store", help="Specify a file where to save logs.") parser.add_argument( "-M", "--runtime-artifact-cleanup", choices=['pass', 'all'], default=None, const='pass', nargs='?', help="""Cleanup test artifacts. The default behavior is 'pass' which only removes artifacts of passing tests. If you wish to remove all artificats including those of failed tests, use 'all'.""") test_xor_generator.add_argument( "-N", "--ninja", action="store_true", default=not any(a in sys.argv for a in ("-k", "--make")), help="Use the Ninja generator with CMake. (This is the default)") test_xor_generator.add_argument( "-k", "--make", action="store_true", help="Use the unix Makefile generator with CMake.") parser.add_argument( "-n", "--no-clean", action="store_true", help="Re-use the outdir before building. Will result in " "faster compilation since builds will be incremental.") parser.add_argument( "--aggressive-no-clean", action="store_true", help="Re-use the outdir before building and do not re-run cmake. Will result in " "much faster compilation since builds will be incremental. This option might " " result in build failures and inconsistencies if dependencies change or when " " applied on a significantly changed code base. Use on your own " " risk. It is recommended to only use this option for local " " development and when testing localized change in a subsystem.") parser.add_argument( '--detailed-test-id', action='store_true', help="Include paths to tests' locations in tests' names. Names will follow " "PATH_TO_TEST/SCENARIO_NAME schema " "e.g. samples/hello_world/sample.basic.helloworld") parser.add_argument( "--no-detailed-test-id", dest='detailed_test_id', action="store_false", help="Don't put paths into tests' names. " "With this arg a test name will be a scenario name " "e.g. sample.basic.helloworld.") # Include paths in names by default. parser.set_defaults(detailed_test_id=True) parser.add_argument( "--detailed-skipped-report", action="store_true", help="Generate a detailed report with all skipped test cases" "including those that are filtered based on testsuite definition." ) parser.add_argument( "-O", "--outdir", default=os.path.join(os.getcwd(), "twister-out"), help="Output directory for logs and binaries. " "Default is 'twister-out' in the current directory. " "This directory will be cleaned unless '--no-clean' is set. " "The '--clobber-output' option controls what cleaning does.") parser.add_argument( "-o", "--report-dir", help="""Output reports containing results of the test run into the specified directory. The output will be both in JSON and JUNIT format (twister.json and twister.xml). """) parser.add_argument("--overflow-as-errors", action="store_true", help="Treat RAM/SRAM overflows as errors.") parser.add_argument("--report-filtered", action="store_true", help="Include filtered tests in the reports.") parser.add_argument("-P", "--exclude-platform", action="append", default=[], help="""Exclude platforms and do not build or run any tests on those platforms. This option can be called multiple times. """ ) parser.add_argument("--persistent-hardware-map", action='store_true', help="""With --generate-hardware-map, tries to use persistent names for serial devices on platforms that support this feature (currently only Linux). """) parser.add_argument( "--vendor", action="append", default=[], help="Vendor filter for testing") parser.add_argument( "-p", "--platform", action="append", default=[], help="Platform filter for testing. This option may be used multiple " "times. Test suites will only be built/run on the platforms " "specified. If this option is not used, then platforms marked " "as default in the platform metadata file will be chosen " "to build and test. ") parser.add_argument( "--platform-reports", action="store_true", help="""Create individual reports for each platform. """) parser.add_argument("--pre-script", help="""specify a pre script. This will be executed before device handler open serial port and invoke runner. """) parser.add_argument( "--quarantine-list", action="append", metavar="FILENAME", help="Load list of test scenarios under quarantine. The entries in " "the file need to correspond to the test scenarios names as in " "corresponding tests .yaml files. These scenarios " "will be skipped with quarantine as the reason.") parser.add_argument( "--quarantine-verify", action="store_true", help="Use the list of test scenarios under quarantine and run them" "to verify their current status.") parser.add_argument( "--report-name", help="""Create a report with a custom name. """) parser.add_argument( "--report-summary", action="store", nargs='?', type=int, const=0, help="Show failed/error report from latest run. Default shows all items found. " "However, you can specify the number of items (e.g. --report-summary 15). " "It also works well with the --outdir switch.") parser.add_argument( "--report-suffix", help="""Add a suffix to all generated file names, for example to add a version or a commit ID. """) parser.add_argument( "--report-all-options", action="store_true", help="""Show all command line options applied, including defaults, as environment.options object in twister.json. Default: show only non-default settings. """) parser.add_argument( "--retry-failed", type=int, default=0, help="Retry failing tests again, up to the number of times specified.") parser.add_argument( "--retry-interval", type=int, default=60, help="Retry failing tests after specified period of time.") parser.add_argument( "--retry-build-errors", action="store_true", help="Retry build errors as well.") parser.add_argument( "-S", "--enable-slow", action="store_true", default="--enable-slow-only" in sys.argv, help="Execute time-consuming test cases that have been marked " "as 'slow' in testcase.yaml. Normally these are only built.") parser.add_argument( "--enable-slow-only", action="store_true", help="Execute time-consuming test cases that have been marked " "as 'slow' in testcase.yaml only. This also set the option --enable-slow") parser.add_argument( "--seed", type=int, help="Seed for native_sim pseudo-random number generator") parser.add_argument( "--short-build-path", action="store_true", help="Create shorter build directory paths based on symbolic links. " "The shortened build path will be used by CMake for generating " "the build system and executing the build. Use this option if " "you experience build failures related to path length, for " "example on Windows OS. This option can be used only with " "'--ninja' argument (to use Ninja build generator).") parser.add_argument( "-t", "--tag", action="append", help="Specify tags to restrict which tests to run by tag value. " "Default is to not do any tag filtering. Multiple invocations " "are treated as a logical 'or' relationship.") parser.add_argument("--timestamps", action="store_true", help="Print all messages with time stamps.") parser.add_argument( "-u", "--no-update", action="store_true", help="Do not update the results of the last run. This option " "is only useful when reusing the same output directory of " "twister, for example when re-running failed tests with --only-failed " "or --no-clean. This option is for debugging purposes only.") parser.add_argument( "-v", "--verbose", action="count", default=0, help="Emit debugging information, call multiple times to increase " "verbosity.") parser.add_argument("-W", "--disable-warnings-as-errors", action="store_true", help="Do not treat warning conditions as errors.") parser.add_argument( "--west-flash", nargs='?', const=[], help="""Uses west instead of ninja or make to flash when running with --device-testing. Supports comma-separated argument list. E.g "twister --device-testing --device-serial /dev/ttyACM0 --west-flash="--board-id=foobar,--erase" will translate to "west flash -- --board-id=foobar --erase" NOTE: device-testing must be enabled to use this option. """ ) parser.add_argument( "--west-runner", help="""Uses the specified west runner instead of default when running with --west-flash. E.g "twister --device-testing --device-serial /dev/ttyACM0 --west-flash --west-runner=pyocd" will translate to "west flash --runner pyocd" NOTE: west-flash must be enabled to use this option. """ ) parser.add_argument( "-X", "--fixture", action="append", default=[], help="Specify a fixture that a board might support.") parser.add_argument( "-x", "--extra-args", action="append", default=[], help="""Extra CMake cache entries to define when building test cases. May be called multiple times. The key-value entries will be prefixed with -D before being passed to CMake. E.g "twister -x=USE_CCACHE=0" will translate to "cmake -DUSE_CCACHE=0" which will ultimately disable ccache. """ ) parser.add_argument( "-y", "--dry-run", action="store_true", help="""Create the filtered list of test cases, but don't actually run them. Useful if you're just interested in the test plan generated for every run and saved in the specified output directory (testplan.json). """) parser.add_argument("extra_test_args", nargs=argparse.REMAINDER, help="Additional args following a '--' are passed to the test binary") parser.add_argument("--alt-config-root", action="append", default=[], help="Alternative test configuration root/s. When a test is found, " "Twister will check if a test configuration file exist in any of " "the alternative test configuration root folders. For example, " "given $test_root/tests/foo/testcase.yaml, Twister will use " "$alt_config_root/tests/foo/testcase.yaml if it exists") return parser def parse_arguments(parser, args, options = None, on_init=True): if options is None: options = parser.parse_args(args) # Very early error handling if options.short_build_path and not options.ninja: logger.error("--short-build-path requires Ninja to be enabled") sys.exit(1) if options.device_serial_pty and os.name == "nt": # OS is Windows logger.error("--device-serial-pty is not supported on Windows OS") sys.exit(1) if options.west_runner and options.west_flash is None: logger.error("west-runner requires west-flash to be enabled") sys.exit(1) if options.west_flash and not options.device_testing: logger.error("west-flash requires device-testing to be enabled") sys.exit(1) if not options.testsuite_root: # if we specify a test scenario which is part of a suite directly, do # not set testsuite root to default, just point to the test directory # directly. if options.test: for scenario in options.test: if dirname := os.path.dirname(scenario): options.testsuite_root.append(dirname) # check again and make sure we have something set if not options.testsuite_root: options.testsuite_root = [os.path.join(ZEPHYR_BASE, "tests"), os.path.join(ZEPHYR_BASE, "samples")] if options.last_metrics or options.compare_report: options.enable_size_report = True if options.footprint_report: options.create_rom_ram_report = True if options.aggressive_no_clean: options.no_clean = True if options.coverage: options.enable_coverage = True if options.enable_coverage and not options.coverage_platform: options.coverage_platform = options.platform if options.coverage_formats: for coverage_format in options.coverage_formats.split(','): if coverage_format not in supported_coverage_formats[options.coverage_tool]: logger.error(f"Unsupported coverage report formats:'{options.coverage_formats}' " f"for {options.coverage_tool}") sys.exit(1) if options.enable_valgrind and not shutil.which("valgrind"): logger.error("valgrind enabled but valgrind executable not found") sys.exit(1) if (not options.device_testing) and (options.device_serial or options.device_serial_pty or options.hardware_map): logger.error("Use --device-testing with --device-serial, or --device-serial-pty, or --hardware-map.") sys.exit(1) if options.device_testing and (options.device_serial or options.device_serial_pty) and len(options.platform) != 1: logger.error("When --device-testing is used with --device-serial " "or --device-serial-pty, exactly one platform must " "be specified") sys.exit(1) if options.device_flash_with_test and not options.device_testing: logger.error("--device-flash-with-test requires --device_testing") sys.exit(1) if options.flash_before and options.device_flash_with_test: logger.error("--device-flash-with-test does not apply when --flash-before is used") sys.exit(1) if options.flash_before and options.device_serial_pty: logger.error("--device-serial-pty cannot be used when --flash-before is set (for now)") sys.exit(1) if options.shuffle_tests and options.subset is None: logger.error("--shuffle-tests requires --subset") sys.exit(1) if options.shuffle_tests_seed and options.shuffle_tests is None: logger.error("--shuffle-tests-seed requires --shuffle-tests") sys.exit(1) if options.size: from twisterlib.size_calc import SizeCalculator for fn in options.size: sc = SizeCalculator(fn, []) sc.size_report() sys.exit(0) if options.footprint_from_buildlog: logger.warning("WARNING: Using --footprint-from-buildlog will give inconsistent results " "for configurations using sysbuild. It is recommended to not use this flag " "when building configurations using sysbuild.") if not options.enable_size_report: logger.error("--footprint-from-buildlog requires --enable-size-report") sys.exit(1) if len(options.extra_test_args) > 0: # extra_test_args is a list of CLI args that Twister did not recognize # and are intended to be passed through to the ztest executable. This # list should begin with a "--". If not, there is some extra # unrecognized arg(s) that shouldn't be there. Tell the user there is a # syntax error. if options.extra_test_args[0] != "--": try: double_dash = options.extra_test_args.index("--") except ValueError: double_dash = len(options.extra_test_args) unrecognized = " ".join(options.extra_test_args[0:double_dash]) logger.error("Unrecognized arguments found: '%s'. Use -- to " "delineate extra arguments for test binary or pass " "-h for help.", unrecognized) sys.exit(1) # Strip off the initial "--" following validation. options.extra_test_args = options.extra_test_args[1:] if on_init and not options.allow_installed_plugin and PYTEST_PLUGIN_INSTALLED: logger.error("By default Twister should work without pytest-twister-harness " "plugin being installed, so please, uninstall it by " "`pip uninstall pytest-twister-harness` and `git clean " "-dxf scripts/pylib/pytest-twister-harness`.") sys.exit(1) elif on_init and options.allow_installed_plugin and PYTEST_PLUGIN_INSTALLED: logger.warning("You work with installed version of " "pytest-twister-harness plugin.") return options def strip_ansi_sequences(s: str) -> str: """Remove ANSI escape sequences from a string.""" return re.sub(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])', "", s) class TwisterEnv: def __init__(self, options=None, default_options=None) -> None: self.version = "Unknown" self.toolchain = None self.commit_date = "Unknown" self.run_date = None self.options = options self.default_options = default_options if options and options.ninja: self.generator_cmd = "ninja" self.generator = "Ninja" else: self.generator_cmd = "make" self.generator = "Unix Makefiles" logger.info(f"Using {self.generator}..") self.test_roots = options.testsuite_root if options else None if options: if not isinstance(options.board_root, list): self.board_roots = [self.options.board_root] else: self.board_roots = self.options.board_root self.outdir = os.path.abspath(options.outdir) else: self.board_roots = None self.outdir = None self.snippet_roots = [Path(ZEPHYR_BASE)] modules = zephyr_module.parse_modules(ZEPHYR_BASE) for module in modules: snippet_root = module.meta.get("build", {}).get("settings", {}).get("snippet_root") if snippet_root: self.snippet_roots.append(Path(module.project) / snippet_root) self.hwm = None self.test_config = options.test_config if options else None self.alt_config_root = options.alt_config_root if options else None def non_default_options(self) -> dict: """Returns current command line options which are set to non-default values.""" diff = {} if not self.options or not self.default_options: return diff dict_options = vars(self.options) dict_default = vars(self.default_options) for k in dict_options.keys(): if k not in dict_default or dict_options[k] != dict_default[k]: diff[k] = dict_options[k] return diff def discover(self): self.check_zephyr_version() self.get_toolchain() self.run_date = datetime.now(timezone.utc).isoformat(timespec='seconds') def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12", "--always"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: _version = subproc.stdout.strip() if _version: self.version = _version logger.info(f"Zephyr version: {self.version}") except OSError: logger.exception("Failure while reading Zephyr version.") if self.version == "Unknown": logger.warning("Could not determine version") try: subproc = subprocess.run(["git", "show", "-s", "--format=%cI", "HEAD"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.commit_date = subproc.stdout.strip() except OSError: logger.exception("Failure while reading head commit date.") @staticmethod def run_cmake_script(args=[]): script = os.fspath(args[0]) logger.debug("Running cmake script %s", script) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', script]) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args log_command(logger, "Calling cmake", cmd) kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() # It might happen that the environment adds ANSI escape codes like \x1b[0m, # for instance if twister is executed from inside a makefile. In such a # scenario it is then necessary to remove them, as otherwise the JSON decoding # will fail. out = strip_ansi_sequences(out.decode()) if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode, "returnmsg": out} return results def get_toolchain(self): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = self.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError(f"E: {result['returnmsg']}") except Exception as e: print(str(e)) sys.exit(2) self.toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{self.toolchain}' toolchain.") ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/environment.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
9,140
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # from enum import Enum import os import json import logging from colorama import Fore import xml.etree.ElementTree as ET import string from datetime import datetime from pathlib import PosixPath from twisterlib.statuses import TwisterStatus logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ReportStatus(str, Enum): def __str__(self): return str(self.value) ERROR = 'error' FAIL = 'failure' SKIP = 'skipped' class Reporting: json_filters = { 'twister.json': { 'deny_suite': ['footprint'] }, 'footprint.json': { 'deny_status': ['FILTER'], 'deny_suite': ['testcases', 'execution_time', 'recording', 'retries', 'runnable'] } } def __init__(self, plan, env) -> None: self.plan = plan #FIXME self.instances = plan.instances self.platforms = plan.platforms self.selected_platforms = plan.selected_platforms self.filtered_platforms = plan.filtered_platforms self.env = env self.timestamp = datetime.now().isoformat() self.outdir = os.path.abspath(env.options.outdir) self.instance_fail_count = plan.instance_fail_count self.footprint = None @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string @staticmethod def xunit_testcase(eleTestsuite, name, classname, status, ts_status, reason, duration, runnable, stats, log, build_only_as_skip): fails, passes, errors, skips = stats if status in [TwisterStatus.SKIP, TwisterStatus.FILTER]: duration = 0 eleTestcase = ET.SubElement( eleTestsuite, "testcase", classname=classname, name=f"{name}", time=f"{duration}") if status in [TwisterStatus.SKIP, TwisterStatus.FILTER]: skips += 1 # temporarily add build_only_as_skip to restore existing CI report behaviour if ts_status == TwisterStatus.PASS and not runnable: tc_type = "build" else: tc_type = status ET.SubElement(eleTestcase, ReportStatus.SKIP, type=f"{tc_type}", message=f"{reason}") elif status in [TwisterStatus.FAIL, TwisterStatus.BLOCK]: fails += 1 el = ET.SubElement(eleTestcase, ReportStatus.FAIL, type="failure", message=f"{reason}") if log: el.text = log elif status == TwisterStatus.ERROR: errors += 1 el = ET.SubElement(eleTestcase, ReportStatus.ERROR, type="failure", message=f"{reason}") if log: el.text = log elif status == TwisterStatus.PASS: if not runnable and build_only_as_skip: ET.SubElement(eleTestcase, ReportStatus.SKIP, type="build", message="built only") skips += 1 else: passes += 1 else: if status == TwisterStatus.NONE: logger.debug(f"{name}: No status") ET.SubElement(eleTestcase, ReportStatus.SKIP, type=f"untested", message="No results captured, testsuite misconfiguration?") else: logger.error(f"{name}: Unknown status '{status}'") return (fails, passes, errors, skips) # Generate a report with all testsuites instead of doing this per platform def xunit_report_suites(self, json_file, filename): json_data = {} with open(json_file, "r") as json_results: json_data = json.load(json_results) env = json_data.get('environment', {}) version = env.get('zephyr_version', None) eleTestsuites = ET.Element('testsuites') all_suites = json_data.get("testsuites", []) suites_to_report = all_suites # do not create entry if everything is filtered out if not self.env.options.detailed_skipped_report: suites_to_report = list(filter(lambda d: d.get('status') != TwisterStatus.FILTER, all_suites)) for suite in suites_to_report: duration = 0 eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=suite.get("name"), time="0", timestamp = self.timestamp, tests="0", failures="0", errors="0", skipped="0") eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) ET.SubElement(eleTSPropetries, 'property', name="platform", value=suite.get("platform")) ET.SubElement(eleTSPropetries, 'property', name="architecture", value=suite.get("arch")) total = 0 fails = passes = errors = skips = 0 handler_time = suite.get('execution_time', 0) runnable = suite.get('runnable', 0) duration += float(handler_time) ts_status = suite.get('status') for tc in suite.get("testcases", []): status = tc.get('status') reason = tc.get('reason', suite.get('reason', 'Unknown')) log = tc.get("log", suite.get("log")) tc_duration = tc.get('execution_time', handler_time) name = tc.get("identifier") classname = ".".join(name.split(".")[:2]) fails, passes, errors, skips = self.xunit_testcase(eleTestsuite, name, classname, status, ts_status, reason, tc_duration, runnable, (fails, passes, errors, skips), log, True) total = errors + passes + fails + skips eleTestsuite.attrib['time'] = f"{duration}" eleTestsuite.attrib['failures'] = f"{fails}" eleTestsuite.attrib['errors'] = f"{errors}" eleTestsuite.attrib['skipped'] = f"{skips}" eleTestsuite.attrib['tests'] = f"{total}" result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) def xunit_report(self, json_file, filename, selected_platform=None, full_report=False): if selected_platform: selected = [selected_platform] logger.info(f"Writing target report for {selected_platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms json_data = {} with open(json_file, "r") as json_results: json_data = json.load(json_results) env = json_data.get('environment', {}) version = env.get('zephyr_version', None) eleTestsuites = ET.Element('testsuites') all_suites = json_data.get("testsuites", []) for platform in selected: suites = list(filter(lambda d: d['platform'] == platform, all_suites)) # do not create entry if everything is filtered out if not self.env.options.detailed_skipped_report: non_filtered = list(filter(lambda d: d.get('status') != TwisterStatus.FILTER, suites)) if not non_filtered: continue duration = 0 eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=platform, timestamp = self.timestamp, time="0", tests="0", failures="0", errors="0", skipped="0") eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) total = 0 fails = passes = errors = skips = 0 for ts in suites: handler_time = ts.get('execution_time', 0) runnable = ts.get('runnable', 0) duration += float(handler_time) ts_status = ts.get('status') # Do not report filtered testcases if ts_status == TwisterStatus.FILTER and not self.env.options.detailed_skipped_report: continue if full_report: for tc in ts.get("testcases", []): status = tc.get('status') reason = tc.get('reason', ts.get('reason', 'Unknown')) log = tc.get("log", ts.get("log")) tc_duration = tc.get('execution_time', handler_time) name = tc.get("identifier") classname = ".".join(name.split(".")[:2]) fails, passes, errors, skips = self.xunit_testcase(eleTestsuite, name, classname, status, ts_status, reason, tc_duration, runnable, (fails, passes, errors, skips), log, True) else: reason = ts.get('reason', 'Unknown') name = ts.get("name") classname = f"{platform}:{name}" log = ts.get("log") fails, passes, errors, skips = self.xunit_testcase(eleTestsuite, name, classname, ts_status, ts_status, reason, duration, runnable, (fails, passes, errors, skips), log, False) total = errors + passes + fails + skips eleTestsuite.attrib['time'] = f"{duration}" eleTestsuite.attrib['failures'] = f"{fails}" eleTestsuite.attrib['errors'] = f"{errors}" eleTestsuite.attrib['skipped'] = f"{skips}" eleTestsuite.attrib['tests'] = f"{total}" result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) def json_report(self, filename, version="NA", platform=None, filters=None): logger.info(f"Writing JSON report {filename}") if self.env.options.report_all_options: report_options = vars(self.env.options) else: report_options = self.env.non_default_options() # Resolve known JSON serialization problems. for k,v in report_options.items(): report_options[k] = str(v) if type(v) in [PosixPath] else v report = {} report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.env.toolchain, "commit_date": self.env.commit_date, "run_date": self.env.run_date, "options": report_options } suites = [] for instance in self.instances.values(): if platform and platform != instance.platform.name: continue if instance.status == TwisterStatus.FILTER and not self.env.options.report_filtered: continue if (filters and 'allow_status' in filters and \ instance.status not in [TwisterStatus[s] for s in filters['allow_status']]): logger.debug(f"Skip test suite '{instance.testsuite.name}' status '{instance.status}' " f"not allowed for {filename}") continue if (filters and 'deny_status' in filters and \ instance.status in [TwisterStatus[s] for s in filters['deny_status']]): logger.debug(f"Skip test suite '{instance.testsuite.name}' status '{instance.status}' " f"denied for {filename}") continue suite = {} handler_log = os.path.join(instance.build_dir, "handler.log") pytest_log = os.path.join(instance.build_dir, "twister_harness.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) used_ram = instance.metrics.get ("used_ram", 0) used_rom = instance.metrics.get("used_rom",0) available_ram = instance.metrics.get("available_ram", 0) available_rom = instance.metrics.get("available_rom", 0) suite = { "name": instance.testsuite.name, "arch": instance.platform.arch, "platform": instance.platform.name, "path": instance.testsuite.source_dir_rel } if instance.run_id: suite['run_id'] = instance.run_id suite["runnable"] = False if instance.status != TwisterStatus.FILTER: suite["runnable"] = instance.run if used_ram: suite["used_ram"] = used_ram if used_rom: suite["used_rom"] = used_rom suite['retries'] = instance.retries if instance.dut: suite["dut"] = instance.dut if available_ram: suite["available_ram"] = available_ram if available_rom: suite["available_rom"] = available_rom if instance.status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: suite['status'] = instance.status suite["reason"] = instance.reason # FIXME if os.path.exists(pytest_log): suite["log"] = self.process_log(pytest_log) elif os.path.exists(handler_log): suite["log"] = self.process_log(handler_log) elif os.path.exists(device_log): suite["log"] = self.process_log(device_log) else: suite["log"] = self.process_log(build_log) elif instance.status == TwisterStatus.FILTER: suite["status"] = TwisterStatus.FILTER suite["reason"] = instance.reason elif instance.status == TwisterStatus.PASS: suite["status"] = TwisterStatus.PASS elif instance.status == TwisterStatus.SKIP: suite["status"] = TwisterStatus.SKIP suite["reason"] = instance.reason if instance.status != TwisterStatus.NONE: suite["execution_time"] = f"{float(handler_time):.2f}" suite["build_time"] = f"{float(instance.build_time):.2f}" testcases = [] if len(instance.testcases) == 1: single_case_duration = f"{float(handler_time):.2f}" else: single_case_duration = 0 for case in instance.testcases: # freeform was set when no sub testcases were parsed, however, # if we discover those at runtime, the fallback testcase wont be # needed anymore and can be removed from the output, it does # not have a status and would otherwise be reported as skipped. if case.freeform and case.status == TwisterStatus.NONE and len(instance.testcases) > 1: continue testcase = {} testcase['identifier'] = case.name if instance.status != TwisterStatus.NONE: if single_case_duration: testcase['execution_time'] = single_case_duration else: testcase['execution_time'] = f"{float(case.duration):.2f}" if case.output != "": testcase['log'] = case.output if case.status == TwisterStatus.SKIP: if instance.status == TwisterStatus.FILTER: testcase["status"] = TwisterStatus.FILTER else: testcase["status"] = TwisterStatus.SKIP testcase["reason"] = case.reason or instance.reason else: testcase["status"] = case.status if case.reason: testcase["reason"] = case.reason testcases.append(testcase) suite['testcases'] = testcases if instance.recording is not None: suite['recording'] = instance.recording if (instance.status not in [TwisterStatus.NONE, TwisterStatus.ERROR, TwisterStatus.FILTER] and self.env.options.create_rom_ram_report and self.env.options.footprint_report is not None): # Init as empty data preparing for filtering properties. suite['footprint'] = {} # Pass suite properties through the context filters. if filters and 'allow_suite' in filters: suite = {k:v for k,v in suite.items() if k in filters['allow_suite']} if filters and 'deny_suite' in filters: suite = {k:v for k,v in suite.items() if k not in filters['deny_suite']} # Compose external data only to these properties which pass filtering. if 'footprint' in suite: do_all = 'all' in self.env.options.footprint_report footprint_files = { 'ROM': 'rom.json', 'RAM': 'ram.json' } for k,v in footprint_files.items(): if do_all or k in self.env.options.footprint_report: footprint_fname = os.path.join(instance.build_dir, v) try: with open(footprint_fname, "rt") as footprint_json: logger.debug(f"Collect footprint.{k} for '{instance.name}'") suite['footprint'][k] = json.load(footprint_json) except FileNotFoundError: logger.error(f"Missing footprint.{k} for '{instance.name}'") # # suites.append(suite) report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("used_ram", int, True), ("used_rom", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: jt = json.load(fp) for ts in jt.get("testsuites", []): d = {} for m, _, _ in interesting_metrics: d[m] = ts.get(m, 0) ts_name = ts.get('name') ts_platform = ts.get('platform') saved_metrics[(ts_name, ts_platform)] = d for instance in self.instances.values(): mkey = (instance.testsuite.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue if show_footprint: logger.log( logging.INFO if all_deltas else logging.WARNING, "{:<25} {:<60} {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testsuite.name, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Found {} footprint deltas to {} as a baseline.".format( warnings, (report if not last_metrics else "the last twister run."))) def synopsis(self): if self.env.options.report_summary == 0: count = self.instance_fail_count log_txt = f"The following issues were found (showing the all {count} items):" elif self.env.options.report_summary: count = self.env.options.report_summary log_txt = f"The following issues were found " if count > self.instance_fail_count: log_txt += f"(presenting {self.instance_fail_count} out of the {count} items requested):" else: log_txt += f"(showing the {count} of {self.instance_fail_count} items):" else: count = 10 log_txt = f"The following issues were found (showing the top {count} items):" cnt = 0 example_instance = None detailed_test_id = self.env.options.detailed_test_id for instance in self.instances.values(): if instance.status not in [TwisterStatus.PASS, TwisterStatus.FILTER, TwisterStatus.SKIP]: cnt += 1 if cnt == 1: logger.info("-+" * 40) logger.info(log_txt) status = instance.status if self.env.options.report_summary is not None and \ status in [TwisterStatus.ERROR, TwisterStatus.FAIL]: status = Fore.RED + status.upper() + Fore.RESET logger.info(f"{cnt}) {instance.testsuite.name} on {instance.platform.name} {status} ({instance.reason})") example_instance = instance if cnt == count: break if cnt == 0 and self.env.options.report_summary is not None: logger.info("-+" * 40) logger.info(f"No errors/fails found") if cnt and example_instance: cwd_rel_path = os.path.relpath(example_instance.testsuite.source_dir, start=os.getcwd()) logger.info("") logger.info("To rerun the tests, call twister using the following commandline:") extra_parameters = '' if detailed_test_id else ' --no-detailed-test-id' logger.info(f"west twister -p <PLATFORM> -s <TEST ID>{extra_parameters}, for example:") logger.info("") logger.info(f"west twister -p {example_instance.platform.name} -s {example_instance.testsuite.name}" f"{extra_parameters}") logger.info(f"or with west:") logger.info(f"west build -p -b {example_instance.platform.name} {cwd_rel_path} -T {example_instance.testsuite.id}") logger.info("-+" * 40) def summary(self, results, ignore_unrecognized_sections, duration): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == TwisterStatus.FAIL: failed += 1 elif not ignore_unrecognized_sections and instance.metrics.get("unrecognized"): logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 # FIXME: need a better way to identify executed tests handler_time = instance.metrics.get('handler_time', 0) if float(handler_time) > 0: run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {}{}{} errored, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, Fore.RED if results.error else Fore.RESET, results.error, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.plan.warnings else Fore.RESET, self.plan.warnings, Fore.RESET, duration)) total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.env.options.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) built_only = results.total - run - results.skipped_configs logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{built_only}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, platform_reports): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: outdir = self.outdir filename = os.path.join(outdir, report_name) if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: json_file = filename + ".json" self.json_report(json_file, version=self.env.version, filters=self.json_filters['twister.json']) if self.env.options.footprint_report is not None: self.json_report(filename + "_footprint.json", version=self.env.version, filters=self.json_filters['footprint.json']) self.xunit_report(json_file, filename + ".xml", full_report=False) self.xunit_report(json_file, filename + "_report.xml", full_report=True) self.xunit_report_suites(json_file, filename + "_suite_report.xml") if platform_reports: self.target_report(json_file, outdir, suffix) def target_report(self, json_file, outdir, suffix): platforms = {repr(inst.platform):inst.platform for _, inst in self.instances.items()} for platform in platforms.values(): if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform.normalized_name, suffix)) json_platform_file = os.path.join(outdir,"{}_{}".format(platform.normalized_name, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform.normalized_name)) json_platform_file = os.path.join(outdir, platform.normalized_name) self.xunit_report(json_file, filename, platform.name, full_report=True) self.json_report(json_platform_file + ".json", version=self.env.version, platform=platform.name, filters=self.json_filters['twister.json']) if self.env.options.footprint_report is not None: self.json_report(json_platform_file + "_footprint.json", version=self.env.version, platform=platform.name, filters=self.json_filters['footprint.json']) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/reports.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
5,908
```python ''' Common code used when logging that is needed by multiple modules. ''' import platform import shlex _WINDOWS = (platform.system() == 'Windows') def log_command(logger, msg, args): '''Platform-independent helper for logging subprocess invocations. Will log a command string that can be copy/pasted into a POSIX shell on POSIX platforms. This is not available on Windows, so the entire args array is logged instead. :param logger: logging.Logger to use :param msg: message to associate with the command :param args: argument list as passed to subprocess module ''' msg = f'{msg}: %s' if _WINDOWS: logger.debug(msg, str(args)) else: logger.debug(msg, shlex.join(args)) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/log_helper.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
166
```python """Module for job counters, limiting the amount of concurrent executions.""" import fcntl import functools import logging import multiprocessing import os import re import select import selectors import subprocess import sys logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class JobHandle: """Small object to handle claim of a job.""" def __init__(self, release_func, *args, **kwargs): self.release_func = release_func self.args = args self.kwargs = kwargs def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): if self.release_func: self.release_func(*self.args, **self.kwargs) class JobClient: """Abstract base class for all job clients.""" def get_job(self): """Claim a job.""" return JobHandle(None) @staticmethod def env(): """Get the environment variables necessary to share the job server.""" return {} @staticmethod def pass_fds(): """Returns the file descriptors that should be passed to subprocesses.""" return [] def popen(self, argv, **kwargs): """Start a process using subprocess.Popen All other arguments are passed to subprocess.Popen. Returns: A Popen object. """ kwargs.setdefault("env", os.environ) kwargs.setdefault("pass_fds", []) kwargs["env"].update(self.env()) kwargs["pass_fds"] += self.pass_fds() return subprocess.Popen( # pylint:disable=consider-using-with argv, **kwargs ) class GNUMakeJobClient(JobClient): """A job client for GNU make. A client of jobserver is allowed to run 1 job without contacting the jobserver, so maintain an optional self._internal_pipe to hold that job. """ def __init__(self, inheritable_pipe, jobs, internal_jobs=0, makeflags=None): self._makeflags = makeflags self._inheritable_pipe = inheritable_pipe self.jobs = jobs self._selector = selectors.DefaultSelector() if internal_jobs: self._internal_pipe = os.pipe() os.write(self._internal_pipe[1], b"+" * internal_jobs) os.set_blocking(self._internal_pipe[0], False) self._selector.register( self._internal_pipe[0], selectors.EVENT_READ, self._internal_pipe[1], ) else: self._internal_pipe = None if self._inheritable_pipe is not None: os.set_blocking(self._inheritable_pipe[0], False) self._selector.register( self._inheritable_pipe[0], selectors.EVENT_READ, self._inheritable_pipe[1], ) def __del__(self): if self._inheritable_pipe: os.close(self._inheritable_pipe[0]) os.close(self._inheritable_pipe[1]) if self._internal_pipe: os.close(self._internal_pipe[0]) os.close(self._internal_pipe[1]) @classmethod def from_environ(cls, env=None, jobs=0): """Create a job client from an environment with the MAKEFLAGS variable. If we are started under a GNU Make Job Server, we can search the environment for a string "--jobserver-auth=R,W", where R and W will be the read and write file descriptors to the pipe respectively. If we don't find this environment variable (or the string inside of it), this will raise an OSError. The specification for MAKEFLAGS is: * If the first char is "n", this is a dry run, just exit. * If the flags contains -j1, go to sequential mode. * If the flags contains --jobserver-auth=R,W AND those file descriptors are valid, use the jobserver. Otherwise output a warning. Args: env: Optionally, the environment to search. jobs: The number of jobs set by the user on the command line. Returns: A GNUMakeJobClient configured appropriately or None if there is no MAKEFLAGS environment variable. """ if env is None: env = os.environ makeflags = env.get("MAKEFLAGS") if not makeflags: return None match = re.search(r"--jobserver-auth=(\d+),(\d+)", makeflags) if match: pipe = [int(x) for x in match.groups()] if jobs: pipe = None logger.warning( "-jN forced on command line; ignoring GNU make jobserver" ) else: try: # Use F_GETFL to see if file descriptors are valid if pipe: rc = fcntl.fcntl(pipe[0], fcntl.F_GETFL) if not rc & os.O_ACCMODE == os.O_RDONLY: logger.warning( "FD %s is not readable (flags=%x); " "ignoring GNU make jobserver", pipe[0], rc) pipe = None if pipe: rc = fcntl.fcntl(pipe[1], fcntl.F_GETFL) if not rc & os.O_ACCMODE == os.O_WRONLY: logger.warning( "FD %s is not writable (flags=%x); " "ignoring GNU make jobserver", pipe[1], rc) pipe = None if pipe: logger.info("using GNU make jobserver") except OSError: pipe = None logger.warning( "No file descriptors; ignoring GNU make jobserver" ) else: pipe = None if not jobs: match = re.search(r"-j(\d+)", makeflags) if match: jobs = int(match.group(1)) if jobs == 1: logger.info("Running in sequential mode (-j1)") if makeflags[0] == "n": logger.info("MAKEFLAGS contained dry-run flag") sys.exit(0) return cls(pipe, jobs, internal_jobs=1, makeflags=makeflags) def get_job(self): """Claim a job. Returns: A JobHandle object. """ while True: ready_items = self._selector.select() if len(ready_items) > 0: read_fd = ready_items[0][0].fd write_fd = ready_items[0][0].data try: byte = os.read(read_fd, 1) return JobHandle( functools.partial(os.write, write_fd, byte) ) except BlockingIOError: pass def env(self): """Get the environment variables necessary to share the job server.""" if self._makeflags: return {"MAKEFLAGS": self._makeflags} flag = "" if self.jobs: flag += f" -j{self.jobs}" if self.jobs != 1 and self._inheritable_pipe is not None: flag += f" --jobserver-auth={self._inheritable_pipe[0]},{self._inheritable_pipe[1]}" return {"MAKEFLAGS": flag} def pass_fds(self): """Returns the file descriptors that should be passed to subprocesses.""" if self.jobs != 1 and self._inheritable_pipe is not None: return self._inheritable_pipe return [] class GNUMakeJobServer(GNUMakeJobClient): """Implements a GNU Make POSIX Job Server. See path_to_url for specification. """ def __init__(self, jobs=0): if not jobs: jobs = multiprocessing.cpu_count() elif jobs > select.PIPE_BUF: jobs = select.PIPE_BUF super().__init__(os.pipe(), jobs) os.write(self._inheritable_pipe[1], b"+" * jobs) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/jobserver.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,672
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import subprocess import sys import os import re import typing import logging from twisterlib.error import TwisterRuntimeError logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "k_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] # Variable below is stored for calculating size using build.log USEFUL_LINES_AMOUNT = 4 def __init__(self, elf_filename: str,\ extra_sections: typing.List[str],\ buildlog_filepath: str = '',\ generate_warning: bool = True): """Constructor @param elf_filename (str) Path to the output binary parsed by objdump to determine section sizes. @param extra_sections (list[str]) List of extra, unexpected sections, which Twister should not report as error and not include in the size calculation. @param buildlog_filepath (str, default: '') Path to the output build.log @param generate_warning (bool, default: True) Twister should (or not) warning about missing the information about footprint. """ self.elf_filename = elf_filename self.buildlog_filename = buildlog_filepath self.sections = [] self.used_rom = 0 self.used_ram = 0 self.available_ram = 0 self.available_rom = 0 self.extra_sections = extra_sections self.is_xip = True self.generate_warning = generate_warning self._calculate_sizes() def size_report(self): print(self.elf_filename) print("SECTION NAME VMA LMA SIZE HEX SZ TYPE") for v in self.sections: print("%-17s 0x%08x 0x%08x %8d 0x%05x %-7s" % (v["name"], v["virt_addr"], v["load_addr"], v["size"], v["size"], v["type"])) print("Totals: %d bytes (ROM), %d bytes (RAM)" % (self.used_rom, self.used_ram)) print("") def get_used_ram(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.used_ram def get_used_rom(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.used_rom def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def get_available_ram(self) -> int: """Get the total available RAM. @return total available RAM, in bytes (int) """ return self.available_ram def get_available_rom(self) -> int: """Get the total available ROM. @return total available ROM, in bytes (int) """ return self.available_rom def _calculate_sizes(self): """ELF file is analyzed, even if the option to read memory footprint from the build.log file is set. This is to detect potential problems contained in unrecognized sections of the file. """ self._analyze_elf_file() if self.buildlog_filename.endswith("build.log"): self._get_footprint_from_buildlog() def _check_elf_file(self) -> None: # Make sure this is an ELF binary with open(self.elf_filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % self.elf_filename) except Exception as e: print(str(e)) sys.exit(2) def _check_is_xip(self) -> None: # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + self.elf_filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % self.elf_filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = len(is_xip_output) != 0 def _get_info_elf_sections(self) -> None: """Calculate RAM and ROM usage and information about issues by section""" objdump_command = "objdump -h " + self.elf_filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True # If build.log file exists, check errors (unrecognized sections # in ELF file). if self.buildlog_filename: if name in SizeCalculator.alloc_sections or \ name in SizeCalculator.rw_sections or \ name in SizeCalculator.ro_sections: continue else: stype = "unknown" if name not in self.extra_sections: recognized = False else: if name in SizeCalculator.alloc_sections: self.used_ram += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.used_ram += size self.used_rom += size stype = "rw" elif name in SizeCalculator.ro_sections: self.used_rom += size if not self.is_xip: self.used_ram += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) def _analyze_elf_file(self) -> None: self._check_elf_file() self._check_is_xip() self._get_info_elf_sections() def _get_buildlog_file_content(self) -> typing.List[str]: """Get content of the build.log file. @return Content of the build.log file (list[str]) """ if os.path.exists(path=self.buildlog_filename): with open(file=self.buildlog_filename, mode='r') as file: file_content = file.readlines() else: if self.generate_warning: logger.error(msg=f"Incorrect path to build.log file to analyze footprints. Please check the path {self.buildlog_filename}.") file_content = [] return file_content def _find_offset_of_last_pattern_occurrence(self, file_content: typing.List[str]) -> int: """Find the offset from which the information about the memory footprint is read. @param file_content (list[str]) Content of build.log. @return Offset with information about the memory footprint (int) """ result = -1 if len(file_content) == 0: logger.warning("Build.log file is empty.") else: # Pattern to first line with information about memory footprint PATTERN_SEARCHED_LINE = "Memory region" # Check the file in reverse order. for idx, line in enumerate(reversed(file_content)): # Condition is fulfilled if the pattern matches with the start of the line. if re.match(pattern=PATTERN_SEARCHED_LINE, string=line): result = idx + 1 break # If the file does not contain information about memory footprint, the warning is raised. if result == -1: logger.warning(msg=f"Information about memory footprint for this test configuration is not found. Please check file {self.buildlog_filename}.") return result def _get_lines_with_footprint(self, start_offset: int, file_content: typing.List[str]) -> typing.List[str]: """Get lines from the file with a memory footprint. @param start_offset (int) Offset with the first line of the information about memory footprint. @param file_content (list[str]) Content of the build.log file. @return Lines with information about memory footprint (list[str]) """ if len(file_content) == 0: result = [] else: if start_offset > len(file_content) or start_offset <= 0: info_line_idx_start = len(file_content) - 1 else: info_line_idx_start = len(file_content) - start_offset info_line_idx_stop = info_line_idx_start + self.USEFUL_LINES_AMOUNT if info_line_idx_stop > len(file_content): info_line_idx_stop = len(file_content) result = file_content[info_line_idx_start:info_line_idx_stop] return result def _clear_whitespaces_from_lines(self, text_lines: typing.List[str]) -> typing.List[str]: """Clear text lines from whitespaces. @param text_lines (list[str]) Lines with useful information. @return Cleared text lines with information (list[str]) """ return [line.strip("\n").rstrip("%") for line in text_lines] if text_lines else [] def _divide_text_lines_into_columns(self, text_lines: typing.List[str]) -> typing.List[typing.List[str]]: """Divide lines of text into columns. @param lines (list[list[str]]) Lines with information about memory footprint. @return Lines divided into columns (list[list[str]]) """ if text_lines: result = [] PATTERN_SPLIT_COLUMNS = " +" for line in text_lines: line = [column.rstrip(":") for column in re.split(pattern=PATTERN_SPLIT_COLUMNS, string=line)] result.append(list(filter(None, line))) else: result = [[]] return result def _unify_prefixes_on_all_values(self, data_lines: typing.List[typing.List[str]]) -> typing.List[typing.List[str]]: """Convert all values in the table to unified order of magnitude. @param data_lines (list[list[str]]) Lines with information about memory footprint. @return Lines with unified values (list[list[str]]) """ if len(data_lines) != self.USEFUL_LINES_AMOUNT: data_lines = [[]] if self.generate_warning: logger.warning(msg=f"Incomplete information about memory footprint. Please check file {self.buildlog_filename}") else: for idx, line in enumerate(data_lines): # Line with description of the columns if idx == 0: continue line_to_replace = list(map(self._binary_prefix_converter, line)) data_lines[idx] = line_to_replace return data_lines def _binary_prefix_converter(self, value: str) -> str: """Convert specific value to particular prefix. @param value (str) Value to convert. @return Converted value to output prefix (str) """ PATTERN_VALUE = r"([0-9]?\s.?B\Z)" if not re.search(pattern=PATTERN_VALUE, string=value): converted_value = value.rstrip() else: PREFIX_POWER = {'B': 0, 'KB': 10, 'MB': 20, 'GB': 30} DEFAULT_DATA_PREFIX = 'B' data_parts = value.split() numeric_value = int(data_parts[0]) unit = data_parts[1] shift = PREFIX_POWER.get(unit, 0) - PREFIX_POWER.get(DEFAULT_DATA_PREFIX, 0) unit_predictor = pow(2, shift) converted_value = str(numeric_value * unit_predictor) return converted_value def _create_data_table(self) -> typing.List[typing.List[str]]: """Create table with information about memory footprint. @return Table with information about memory usage (list[list[str]]) """ file_content = self._get_buildlog_file_content() data_line_start_idx = self._find_offset_of_last_pattern_occurrence(file_content=file_content) if data_line_start_idx < 0: data_from_content = [[]] else: # Clean lines and separate information to columns information_lines = self._get_lines_with_footprint(start_offset=data_line_start_idx, file_content=file_content) information_lines = self._clear_whitespaces_from_lines(text_lines=information_lines) data_from_content = self._divide_text_lines_into_columns(text_lines=information_lines) data_from_content = self._unify_prefixes_on_all_values(data_lines=data_from_content) return data_from_content def _get_footprint_from_buildlog(self) -> None: """Get memory footprint from build.log""" data_from_file = self._create_data_table() if data_from_file == [[]] or not data_from_file: self.used_ram = 0 self.used_rom = 0 self.available_ram = 0 self.available_rom = 0 if self.generate_warning: logger.warning(msg=f"Missing information about memory footprint. Check file {self.buildlog_filename}.") else: ROW_RAM_IDX = 2 ROW_ROM_IDX = 1 COLUMN_USED_SIZE_IDX = 1 COLUMN_AVAILABLE_SIZE_IDX = 2 self.used_ram = int(data_from_file[ROW_RAM_IDX][COLUMN_USED_SIZE_IDX]) self.used_rom = int(data_from_file[ROW_ROM_IDX][COLUMN_USED_SIZE_IDX]) self.available_ram = int(data_from_file[ROW_RAM_IDX][COLUMN_AVAILABLE_SIZE_IDX]) self.available_rom = int(data_from_file[ROW_ROM_IDX][COLUMN_AVAILABLE_SIZE_IDX]) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/size_calc.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
3,666
```python #!/usr/bin/env python3 # vim: set syntax=python ts=4 : # import os import scl from twisterlib.config_parser import TwisterConfigParser from twisterlib.environment import ZEPHYR_BASE class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.normalized_name = "" # if sysbuild to be used by default on a given platform self.sysbuild = False self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.timeout_multiplier = 1.0 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.vendor = "" self.tier = -1 self.type = "na" self.simulation = "na" self.simulation_exec = None self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() self.uart = "" self.resc = "" def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.normalized_name = self.name.replace("/", "_") self.sysbuild = data.get("sysbuild", False) self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.timeout_multiplier = testing.get("timeout_multiplier", 1.0) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) self.binaries = testing.get("binaries", []) renode = testing.get("renode", {}) self.uart = renode.get("uart", "") self.resc = renode.get("resc", "") # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.vendor = data.get('vendor', '') self.tier = data.get("tier", -1) self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.simulation_exec = data.get('simulation_exec') self.supported_toolchains = data.get("toolchain", []) if self.supported_toolchains is None: self.supported_toolchains = [] support_toolchain_variants = { # we don't provide defaults for 'arc' intentionally: some targets can't be built with GNU # toolchain ("zephyr", "cross-compile", "xtools" options) and for some targets we haven't # provided MWDT compiler / linker options in corresponding SoC file in Zephyr, so these # targets can't be built with ARC MWDT toolchain ("arcmwdt" option) by Zephyr build system # Instead for 'arc' we rely on 'toolchain' option in board yaml configuration. "arm": ["zephyr", "gnuarmemb", "xtools", "armclang", "llvm"], "arm64": ["zephyr", "cross-compile"], "mips": ["zephyr", "xtools"], "nios2": ["zephyr", "xtools"], "riscv": ["zephyr", "cross-compile"], "posix": ["host", "llvm"], "sparc": ["zephyr", "xtools"], "x86": ["zephyr", "xtools", "llvm"], # Xtensa is not listed on purpose, since there is no single toolchain # that is supported on all board targets for xtensa. } if self.arch in support_toolchain_variants: for toolchain in support_toolchain_variants[self.arch]: if toolchain not in self.supported_toolchains: self.supported_toolchains.append(toolchain) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) ```
/content/code_sandbox/scripts/pylib/twister/twisterlib/platform.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,112
```python #!/usr/bin/env python3 # # """ Stack compressor for FlameGraph This translate stack samples captured by perf subsystem into format used by flamegraph.pl. Translation uses .elf file to get function names from addresses Usage: ./script/perf/stackcollapse.py <file with perf printbuf output> <ELF file> """ import re import sys import struct import binascii from functools import lru_cache from elftools.elf.elffile import ELFFile @lru_cache(maxsize=None) def addr_to_sym(addr, elf): symtab = elf.get_section_by_name(".symtab") for sym in symtab.iter_symbols(): if sym.entry.st_info.type == "STT_FUNC" and sym.entry.st_value <= addr < sym.entry.st_value + sym.entry.st_size: return sym.name if addr == 0: return "nullptr" return "[unknown]" def collapse(buf, elf): while buf: count, = struct.unpack_from(">Q", buf) assert count > 0 addrs = struct.unpack_from(f">{count}Q", buf, 8) func_trace = reversed(list(map(lambda a: addr_to_sym(a, elf), addrs))) prev_func = next(func_trace) line = prev_func # merge dublicate functions for func in func_trace: if prev_func != func: prev_func = func line += ";" + func print(line, 1) buf = buf[8 + 8 * count:] if __name__ == "__main__": elf = ELFFile(open(sys.argv[2], "rb")) with open(sys.argv[1], "r") as f: inp = f.read() lines = inp.splitlines() assert int(re.match(r"Perf buf length (\d+)", lines[0]).group(1)) == len(lines) - 1 buf = binascii.unhexlify("".join(lines[1:])) collapse(buf, elf) ```
/content/code_sandbox/scripts/profiling/stackcollapse.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
434
```python #!/usr/bin/env python3 # # """ Script to capture tracing data with UART backend. """ import sys import serial import argparse def parse_args(): global args parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) parser.add_argument("-d", "--serial_port", required=True, help="serial port") parser.add_argument("-b", "--serial_baudrate", required=True, help="serial baudrate") parser.add_argument("-o", "--output", default='channel0_0', required=False, help="tracing data output file") args = parser.parse_args() def main(): parse_args() serial_port = args.serial_port serial_baudrate = args.serial_baudrate output_file = args.output try: ser = serial.Serial(serial_port, serial_baudrate) ser.isOpen() except serial.SerialException as e: sys.exit("{}".format(e)) print("serial open success") #enable device tracing ser.write("enable\r".encode()) with open(output_file, "wb") as file_desc: while True: count = ser.inWaiting() if count > 0: while count > 0: data = ser.read() file_desc.write(data) count -= 1 ser.close() if __name__=="__main__": try: main() except KeyboardInterrupt: print('Data capture interrupted, data saved into {}'.format(args.output)) sys.exit(0) ```
/content/code_sandbox/scripts/tracing/trace_capture_uart.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
335
```python """ The classes below are examples of user-defined CommitRules. Commit rules are gitlint rules that act on the entire commit at once. Once the rules are discovered, gitlint will automatically take care of applying them to the entire commit. This happens exactly once per commit. A CommitRule contrasts with a LineRule (see examples/my_line_rules.py) in that a commit rule is only applied once on an entire commit. This allows commit rules to implement more complex checks that span multiple lines and/or checks that should only be done once per gitlint run. While every LineRule can be implemented as a CommitRule, it's usually easier and more concise to go with a LineRule if that fits your needs. """ from gitlint.rules import CommitRule, RuleViolation, CommitMessageTitle, LineRule, CommitMessageBody from gitlint.options import IntOption, StrOption import re class BodyMinLineCount(CommitRule): # A rule MUST have a human friendly name name = "body-min-line-count" # A rule MUST have an *unique* id, we recommend starting with UC (for User-defined Commit-rule). id = "UC6" # A rule MAY have an options_spec if its behavior should be configurable. options_spec = [IntOption('min-line-count', 1, "Minimum body line count excluding Signed-off-by")] def validate(self, commit): filtered = [x for x in commit.message.body if not x.lower().startswith("signed-off-by") and x != ''] line_count = len(filtered) min_line_count = self.options['min-line-count'].value if line_count < min_line_count: message = "Commit message body is empty, should at least have {} line(s).".format(min_line_count) return [RuleViolation(self.id, message, line_nr=1)] class BodyMaxLineCount(CommitRule): # A rule MUST have a human friendly name name = "body-max-line-count" # A rule MUST have an *unique* id, we recommend starting with UC (for User-defined Commit-rule). id = "UC1" # A rule MAY have an options_spec if its behavior should be configurable. options_spec = [IntOption('max-line-count', 200, "Maximum body line count")] def validate(self, commit): line_count = len(commit.message.body) max_line_count = self.options['max-line-count'].value if line_count > max_line_count: message = "Commit message body contains too many lines ({0} > {1})".format(line_count, max_line_count) return [RuleViolation(self.id, message, line_nr=1)] class SignedOffBy(CommitRule): """ This rule will enforce that each commit contains a "Signed-off-by" line. We keep things simple here and just check whether the commit body contains a line that starts with "Signed-off-by". """ # A rule MUST have a human friendly name name = "body-requires-signed-off-by" # A rule MUST have an *unique* id, we recommend starting with UC (for User-defined Commit-rule). id = "UC2" def validate(self, commit): flags = re.UNICODE flags |= re.IGNORECASE for line in commit.message.body: if line.lower().startswith("signed-off-by"): if not re.search(r"(^)Signed-off-by: ([-'\w.]+) ([-'\w.]+) (.*)", line, flags=flags): return [RuleViolation(self.id, "Signed-off-by: must have a full name", line_nr=1)] else: return return [RuleViolation(self.id, "Commit message does not contain a 'Signed-off-by:' line", line_nr=1)] class TitleMaxLengthRevert(LineRule): name = "title-max-length-no-revert" id = "UC5" target = CommitMessageTitle options_spec = [IntOption('line-length', 75, "Max line length")] violation_message = "Commit title exceeds max length ({0}>{1})" def validate(self, line, _commit): max_length = self.options['line-length'].value if len(line) > max_length and not line.startswith("Revert"): return [RuleViolation(self.id, self.violation_message.format(len(line), max_length), line)] class TitleStartsWithSubsystem(LineRule): name = "title-starts-with-subsystem" id = "UC3" target = CommitMessageTitle options_spec = [StrOption('regex', ".*", "Regex the title should match")] def validate(self, title, _commit): regex = self.options['regex'].value pattern = re.compile(regex, re.UNICODE) violation_message = "Commit title does not follow [subsystem]: [subject] (and should not start with literal subsys or treewide)" if not pattern.search(title): return [RuleViolation(self.id, violation_message, title)] class MaxLineLengthExceptions(LineRule): name = "max-line-length-with-exceptions" id = "UC4" target = CommitMessageBody options_spec = [IntOption('line-length', 75, "Max line length")] violation_message = "Commit message body line exceeds max length ({0}>{1})" def validate(self, line, _commit): max_length = self.options['line-length'].value urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line) if line.lower().startswith('signed-off-by') or line.lower().startswith('co-authored-by'): return if urls: return if len(line) > max_length: return [RuleViolation(self.id, self.violation_message.format(len(line), max_length), line)] class BodyContainsBlockedTags(LineRule): name = "body-contains-blocked-tags" id = "UC7" target = CommitMessageBody tags = ["Change-Id"] def validate(self, line, _commit): flags = re.IGNORECASE for tag in self.tags: if re.search(rf"^\s*{tag}:", line, flags=flags): return [RuleViolation(self.id, f"Commit message contains a blocked tag: {tag}")] return ```
/content/code_sandbox/scripts/gitlint/zephyr_commit_rules.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,384
```python #!/usr/bin/env python3 # # """ Script to parse CTF data and print to the screen in a custom and colorful format. Generate trace using samples/subsys/tracing for example: west build -b qemu_x86 samples/subsys/tracing -t run \ -- -DCONF_FILE=prj_uart_ctf.conf mkdir ctf cp build/channel0_0 ctf/ cp subsys/tracing/ctf/tsdl/metadata ctf/ ./scripts/tracing/parse_ctf.py -t ctf """ import sys import datetime import colorama from colorama import Fore import argparse try: import bt2 except ImportError: sys.exit("Missing dependency: You need to install python bindings of babeltrace.") def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) parser.add_argument("-t", "--trace", required=True, help="tracing data (directory with metadata and trace file)") args = parser.parse_args() return args def main(): colorama.init() args = parse_args() msg_it = bt2.TraceCollectionMessageIterator(args.trace) last_event_ns_from_origin = None timeline = [] def get_thread(name): for t in timeline: if t.get('name', None) == name and t.get('in', 0 ) != 0 and not t.get('out', None): return t return {} for msg in msg_it: if not isinstance(msg, bt2._EventMessageConst): continue ns_from_origin = msg.default_clock_snapshot.ns_from_origin event = msg.event # Compute the time difference since the last event message. diff_s = 0 if last_event_ns_from_origin is not None: diff_s = (ns_from_origin - last_event_ns_from_origin) / 1e9 dt = datetime.datetime.fromtimestamp(ns_from_origin / 1e9) if event.name in [ 'thread_switched_out', 'thread_switched_in', 'thread_pending', 'thread_ready', 'thread_resume', 'thread_suspend', 'thread_create', 'thread_abort' ]: cpu = event.payload_field.get("cpu", None) thread_id = event.payload_field.get("thread_id", None) thread_name = event.payload_field.get("name", None) th = {} if event.name in ['thread_switched_out', 'thread_switched_in'] and cpu is not None: cpu_string = f"(cpu: {cpu})" else: cpu_string = "" if thread_name: print(f"{dt} (+{diff_s:.6f} s): {event.name}: {thread_name} {cpu_string}") elif thread_id: print(f"{dt} (+{diff_s:.6f} s): {event.name}: {thread_id} {cpu_string}") else: print(f"{dt} (+{diff_s:.6f} s): {event.name}") if event.name in ['thread_switched_out', 'thread_switched_in']: if thread_name: th = get_thread(thread_name) if not th: th['name'] = thread_name else: th = get_thread(thread_id) if not th: th['name'] = thread_id if event.name in ['thread_switched_out']: th['out'] = ns_from_origin tin = th.get('in', None) tout = th.get('out', None) if tout is not None and tin is not None: diff = tout - tin th['runtime'] = diff elif event.name in ['thread_switched_in']: th['in'] = ns_from_origin timeline.append(th) elif event.name in ['thread_info']: stack_size = event.payload_field['stack_size'] print(f"{dt} (+{diff_s:.6f} s): {event.name} (Stack size: {stack_size})") elif event.name in ['start_call', 'end_call']: if event.payload_field['id'] == 39: c = Fore.GREEN elif event.payload_field['id'] in [37, 38]: c = Fore.CYAN else: c = Fore.YELLOW print(c + f"{dt} (+{diff_s:.6f} s): {event.name} {event.payload_field['id']}" + Fore.RESET) elif event.name in ['semaphore_init', 'semaphore_take', 'semaphore_give']: c = Fore.CYAN print(c + f"{dt} (+{diff_s:.6f} s): {event.name} ({event.payload_field['id']})" + Fore.RESET) elif event.name in ['mutex_init', 'mutex_take', 'mutex_give']: c = Fore.MAGENTA print(c + f"{dt} (+{diff_s:.6f} s): {event.name} ({event.payload_field['id']})" + Fore.RESET) else: print(f"{dt} (+{diff_s:.6f} s): {event.name}") last_event_ns_from_origin = ns_from_origin if __name__=="__main__": main() ```
/content/code_sandbox/scripts/tracing/parse_ctf.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,143
```python #!/usr/bin/env python3 # # """ Script to capture tracing data with USB backend. """ import usb.core import usb.util import argparse import sys def parse_args(): global args parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, allow_abbrev=False) parser.add_argument("-v", "--vendor_id", required=True, help="usb device vendor id") parser.add_argument("-p", "--product_id", required=True, help="usb device product id") parser.add_argument("-o", "--output", default='channel0_0', required=False, help="tracing data output file") args = parser.parse_args() def main(): parse_args() if args.vendor_id.isdecimal(): vendor_id = int(args.vendor_id) else: vendor_id = int(args.vendor_id, 16) if args.product_id.isdecimal(): product_id = int(args.product_id) else: product_id = int(args.product_id, 16) output_file = args.output try: usb_device = usb.core.find(idVendor=vendor_id, idProduct=product_id) except Exception as e: sys.exit("{}".format(e)) if usb_device is None: sys.exit("No device found, check vendor_id and product_id") if usb_device.is_kernel_driver_active(0): try: usb_device.detach_kernel_driver(0) except usb.core.USBError as e: sys.exit("{}".format(e)) # set the active configuration. With no arguments, the first # configuration will be the active one try: usb_device.set_configuration() except usb.core.USBError as e: sys.exit("{}".format(e)) configuration = usb_device[0] interface = configuration[(0, 0)] # match the only IN endpoint read_endpoint = usb.util.find_descriptor(interface, custom_match = \ lambda e: \ usb.util.endpoint_direction( \ e.bEndpointAddress) == \ usb.util.ENDPOINT_IN) # match the only OUT endpoint write_endpoint = usb.util.find_descriptor(interface, custom_match = \ lambda e: \ usb.util.endpoint_direction( \ e.bEndpointAddress) == \ usb.util.ENDPOINT_OUT) usb.util.claim_interface(usb_device, interface) #enable device tracing write_endpoint.write('enable') #try to read to avoid garbage mixed to useful stream data buff = usb.util.create_buffer(8192) read_endpoint.read(buff, 10000) with open(output_file, "wb") as file_desc: while True: buff = usb.util.create_buffer(8192) length = read_endpoint.read(buff, 100000) for index in range(length): file_desc.write(chr(buff[index]).encode('latin1')) usb.util.release_interface(usb_device, interface) if __name__=="__main__": try: main() except KeyboardInterrupt: print('Data capture interrupted, data saved into {}'.format(args.output)) sys.exit(0) ```
/content/code_sandbox/scripts/tracing/trace_capture_usb.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
663
```python #!/usr/bin/env python3 """Format HTTP Status codes for use in a C header This script extracts HTTP status codes from mozilla.org and formats them to fit inside of a C enum along with comments. The output may appear somewhat redundant but it strives to a) be human readable b) eliminate the need to look up status manually, c) be machine parseable for table generation The output is sorted for convenience. Usage: ./scripts/net/enumerate_http_status.py HTTP_100_CONTINUE = 100, /**< Continue */ ... HTTP_418_IM_A_TEAPOT = 418, /**< I'm a teapot */ ... HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511, /**< Network Authentication Required */ """ from lxml import html import requests import re page = requests.get('path_to_url tree = html.fromstring(page.content) codes = tree.xpath('//code/text()') codes2 = {} for c in codes: if re.match('[0-9][0-9][0-9] [a-zA-Z].*', c): key = int(c[0:3]) val = c[4:] codes2[key] = val keys = sorted(codes2.keys()) for key in keys: val = codes2[key] enum_head = 'HTTP' enum_body = f'{key}' enum_tail = val.upper().replace(' ', '_').replace("'", '').replace('-', '_') enum_label = '_'.join([enum_head, enum_body, enum_tail]) comment = f'/**< {val} */' print(f'{enum_label} = {key}, {comment}') ```
/content/code_sandbox/scripts/net/enumerate_http_status.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
350
```python #!/usr/bin/env python3 import subprocess import tempfile import argparse import os import string import sys quartus_cpf_template = """<?xml version="1.0" encoding="US-ASCII" standalone="yes"?> <cof> <output_filename>${OUTPUT_FILENAME}</output_filename> <n_pages>1</n_pages> <width>1</width> <mode>14</mode> <sof_data> <user_name>Page_0</user_name> <page_flags>1</page_flags> <bit0> <sof_filename>${SOF_FILENAME}<compress_bitstream>1</compress_bitstream></sof_filename> </bit0> </sof_data> <version>10</version> <create_cvp_file>0</create_cvp_file> <create_hps_iocsr>0</create_hps_iocsr> <auto_create_rpd>0</auto_create_rpd> <rpd_little_endian>1</rpd_little_endian> <options> <map_file>1</map_file> </options> <MAX10_device_options> <por>0</por> <io_pullup>1</io_pullup> <config_from_cfm0_only>0</config_from_cfm0_only> <isp_source>0</isp_source> <verify_protect>0</verify_protect> <epof>0</epof> <ufm_source>2</ufm_source> <ufm_filepath>${KERNEL_FILENAME}</ufm_filepath> </MAX10_device_options> <advanced_options> <ignore_epcs_id_check>2</ignore_epcs_id_check> <ignore_condone_check>2</ignore_condone_check> <plc_adjustment>0</plc_adjustment> <post_chain_bitstream_pad_bytes>-1</post_chain_bitstream_pad_bytes> <post_device_bitstream_pad_bytes>-1</post_device_bitstream_pad_bytes> <bitslice_pre_padding>1</bitslice_pre_padding> </advanced_options> </cof> """ # XXX Do we care about FileRevision, DefaultMfr, PartName? Do they need # to be parameters? So far seems to work across 2 different boards, leave # this alone for now. quartus_pgm_template = """/* Quartus Prime Version 16.0.0 Build 211 04/27/2016 SJ Lite Edition */ JedecChain; FileRevision(JESD32A); DefaultMfr(6E); P ActionCode(Cfg) Device PartName(10M50DAF484ES) Path("${POF_DIR}/") File("${POF_FILE}") MfrSpec(OpMask(1)); ChainEnd; AlteraBegin; ChainType(JTAG); AlteraEnd;""" def create_pof(input_sof, kernel_hex): """given an input CPU .sof file and a kernel binary, return a file-like object containing .pof data suitable for flashing onto the device""" t = string.Template(quartus_cpf_template) output_pof = tempfile.NamedTemporaryFile(suffix=".pof") input_sof = os.path.abspath(input_sof) kernel_hex = os.path.abspath(kernel_hex) # These tools are very stupid and freak out if the desired filename # extensions are used. The kernel image must have extension .hex with tempfile.NamedTemporaryFile(suffix=".cof") as temp_xml: xml = t.substitute(SOF_FILENAME=input_sof, OUTPUT_FILENAME=output_pof.name, KERNEL_FILENAME=kernel_hex) temp_xml.write(bytes(xml, 'UTF-8')) temp_xml.flush() cmd = ["quartus_cpf", "-c", temp_xml.name] try: subprocess.check_output(cmd) except subprocess.CalledProcessError as cpe: sys.exit(cpe.output.decode("utf-8") + "\nFailed to create POF file") return output_pof def flash_kernel(device_id, input_sof, kernel_hex): pof_file = create_pof(input_sof, kernel_hex) with tempfile.NamedTemporaryFile(suffix=".cdf") as temp_cdf: dname, fname = os.path.split(pof_file.name) t = string.Template(quartus_pgm_template) cdf = t.substitute(POF_DIR=dname, POF_FILE=fname) temp_cdf.write(bytes(cdf, 'UTF-8')) temp_cdf.flush() cmd = ["quartus_pgm", "-c", device_id, temp_cdf.name] try: subprocess.check_output(cmd) except subprocess.CalledProcessError as cpe: sys.exit(cpe.output.decode("utf-8") + "\nFailed to flash image") pof_file.close() def main(): parser = argparse.ArgumentParser(description="Flash zephyr onto Altera boards", allow_abbrev=False) parser.add_argument("-s", "--sof", help=".sof file with Nios II CPU configuration") parser.add_argument("-k", "--kernel", help="Zephyr kernel image to place into UFM in Intel HEX format") parser.add_argument("-d", "--device", help="Remote device identifier / cable name. Default is " "USB-BlasterII. Run jtagconfig -n if unsure.", default="USB-BlasterII") args = parser.parse_args() flash_kernel(args.device, args.sof, args.kernel) if __name__ == "__main__": main() ```
/content/code_sandbox/scripts/support/quartus-flash.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
1,222
```shell #!/bin/bash image=net-tools name=net-tools network=net-tools0 zephyr_pid=0 docker_pid=0 configuration="" result=0 dirs="" zephyr_overlay="" docker_test_script_name=docker-test.sh scan_dirs=0 RUNNING_FROM_MAIN_SCRIPT=1 check_dirs () { local ret_zephyr=0 local ret_net_tools=0 if [ -z "$ZEPHYR_BASE" ]; then echo '$ZEPHYR_BASE is unset' >&2 ret_zephyr=1 elif [ ! -d "$ZEPHYR_BASE" ]; then echo '$ZEPHYR_BASE is set, but it is not a directory' >&2 ret_zephyr=1 fi if [ -z "$NET_TOOLS_BASE" ]; then local d for d in "$ZEPHYR_BASE/../.." "$ZEPHYR_BASE/.." do local l l="$d/tools/net-tools" if [ -d "$l" ]; then NET_TOOLS_BASE="$l" break fi done fi if [ $ret_zephyr -eq 0 ]; then echo "\$ZEPHYR_BASE $ZEPHYR_BASE" fi if [ -z "$NET_TOOLS_BASE" ]; then echo '$NET_TOOLS_BASE is unset, no net-tools found' >&2 ret_net_tools=1 elif [ ! -d "$NET_TOOLS_BASE" ]; then echo '$NET_TOOLS_BASE set, but it is not a directory' >&2 ret_net_tools=1 fi if [ $ret_net_tools -eq 0 ]; then echo "\$NET_TOOLS_BASE $NET_TOOLS_BASE" fi if [ $ret_zephyr -ne 0 -o $ret_net_tools -ne 0 ]; then return 1 fi return 0 } scan_dirs () { echo echo "Following directories under $ZEPHYR_BASE can be used by this script:" find "$ZEPHYR_BASE" -type f -name $docker_test_script_name | \ awk -F "$ZEPHYR_BASE/" '{ print $2 }' | \ sed "s/\/$docker_test_script_name//" } start_configuration () { local bridge_interface="" local addresses="--ip=192.0.2.2 --ip6=2001:db8::2" if ! docker image ls | grep "$image" > /dev/null; then echo "Docker image '$image' not found" >&2 return 1 fi if ! docker network ls | grep "$network" > /dev/null; then bridge_interface=$("$NET_TOOLS_BASE/net-setup.sh" \ --config "$NET_TOOLS_BASE/docker.conf" \ start 2>/dev/null | tail -1) if [ $? != 0 ]; then echo "Could not start Docker network '$network'" >&2 return 1 fi echo "Started Docker network '$network' bridge interface" \ "'$bridge_interface'..." fi if [ -n "$*" ]; then addresses="$*" fi if docker ps | grep "$name" > /dev/null; then docker stop "$name" fi if docker run --hostname=$name --name=$name $addresses \ --rm -dit --network=$network $image > /dev/null; then echo -n "Started Docker container '$name'" if [ -n "$*" ]; then echo -n " with extra arguments '$*'" fi echo "..." else echo "Could not start Docker container '$image'" return 1 fi } stop_configuration () { local bridge_interface="" if docker ps | grep "$name" > /dev/null; then docker stop "$name" > /dev/null if [ $? -eq 0 ]; then echo "Stopped Docker container '$name'..." else echo "Could not stop Docker container '$name'" >&2 fi fi bridge_interface=$(docker network ls | grep "$network" | cut -d " " -f 1) if [ -n "$bridge_interface" ]; then docker network rm "$network" > /dev/null if [ $? -eq 0 ]; then echo "Stopped Docker network '$network' bridge interface" \ "'br-$bridge_interface'..." else echo "Could not stop Docker network '$network'" >&2 fi fi # No need to keep the zephyr eth interface around "$NET_TOOLS_BASE/net-setup.sh" --config "$NET_TOOLS_BASE/docker.conf" \ stop > /dev/null 2>&1 } start_zephyr () { if [ -n "$*" ]; then echo "Building Zephyr with additional arguments '$@'..." >&2 fi rm -rf build && mkdir build && \ cmake -GNinja -DBOARD=native_sim -B build "$@" . && \ ninja -C build # Run the binary directly so that ninja does not print errors that # could be confusing. #ninja -C build run & build/zephyr/zephyr.exe & zephyr_pid=$! sleep 3 echo "Zephyr PID $zephyr_pid" } list_children () { local pid="$(ps -o pid= --ppid "$1")" for p in $pid do list_children $p done if [ -n "$pid" ]; then echo -n "$pid " fi } stop_zephyr () { if [ "$zephyr_pid" -ne 0 ]; then local zephyrs="$zephyr_pid $(list_children "$zephyr_pid")" echo "Stopping Zephyr PIDs $zephyrs" kill $zephyrs 2> /dev/null fi zephyr_pid=0 } wait_zephyr () { local result="" echo "Waiting for Zephyr $zephyr_pid..." wait $zephyr_pid result=$? zephyr_pid=0 return $result } docker_run () { local test="" local result=0 for test in "$@" do echo "Running '$test' in the container..." docker container exec net-tools $test || return $? done } start_docker () { docker_run "$@" & docker_pid=$! echo "Docker PID $docker_pid" } stop_docker () { if [ "$docker_pid" -ne 0 -a "$configuration" != "keep" ]; then local dockers="$docker_pid $(list_children "$docker_pid")" echo "Stopping Docker PIDs $dockers" kill $dockers 2> /dev/null fi docker_pid=0 } wait_docker () { local result="" echo "Waiting for Docker PID $docker_pid..." wait $docker_pid result=$? docker_pid=0 echo "Docker returned '$result'" return $result } run_test () { local test="$(basename $(pwd))" local result=0 local overlay="" if [ -n "$zephyr_overlay" ]; then overlay="-DOVERLAY_CONFIG=$zephyr_overlay" fi source "$1" result=$? if [ $result -eq 0 ]; then echo "Sample '$test' successful" else echo "Sample '$test' failed with return value '$result'" fi return $result } usage () { BASENAME=`basename $0` cat <<EOF $BASENAME [-Z <zephyr base directory>] [-N <net-tools base directory>] [<list of test directories>] This script runs Zephyr sample tests using Docker container and network implemented by the 'net-tools' subproject. -Z|--zephyr-dir <dir> set Zephyr base directory -N|--net-tools-dir <dir> set net-tools directory --start only start Docker container and network and exit --stop only stop Docker container and network --keep keep Docker container and network after test --overlay <config files> additional configuration/overlay files for the Zephyr build process --scan find out the directories that can be used for this testing <list of test directories> run the tests in these directories instead of current directory The automatically detected directories are: EOF check_dirs } stop_sample_test () { echo "Interrupted..." >&2 stop_zephyr stop_docker stop_configuration exit 2 } trap stop_sample_test ABRT INT HUP TERM while test -n "$1" do case "$1" in -Z|--zephyr-dir) shift ZEPHYR_BASE="$1" ;; -N|--net-tools-dir) shift NET_TOOLS_BASE="$1" ;; -h|--help) usage exit ;; --start) if [ -n "$configuration" ]; then echo "--start or --stop specified multiple times" >&2 exit 1 fi configuration=start_only ;; --stop) if [ -n "$configuration" ]; then echo "--start or --stop specified multiple times" >&2 exit 1 fi configuration=stop_only ;; --keep) configuration=keep ;; --overlay) shift if [ -n "$zephyr_overlay" ]; then zephyr_overlay="$zephyr_overlay $1" else zephyr_overlay="$1" fi ;; --scan) scan_dirs=1 ;; -*) echo "Argument '$1' not recognised" >&2 usage return 0 ;; *) dirs="$dirs $1" ;; esac shift done check_dirs || exit $? if [ $scan_dirs -eq 1 ]; then scan_dirs exit 0 fi if [ -z "$configuration" -o "$configuration" = "start_only" -o \ "$configuration" = "keep" ]; then if [ "$configuration" = start_only ]; then start_configuration result=$? else result=0 found=0 if [ -z "$dirs" ]; then dirs="." fi for d in $dirs; do if [ ! -d "$d" ]; then echo "No such directory $d, skipping it" continue fi if [ ! -f "$d/$docker_test_script_name" ]; then echo "No such file $d/$docker_test_script_name, skipping directory" continue fi found=$(expr $found + 1) CURR_DIR=`pwd` cd "$d" run_test "./$docker_test_script_name" test_result=$? cd "$CURR_DIR" if [ $test_result -ne 0 ]; then result=1 fi done if [ $found -eq 0 ]; then exit 1 fi fi fi if [ -z "$configuration" -o "$configuration" = stop_only ]; then stop_configuration fi exit $result ```
/content/code_sandbox/scripts/net/run-sample-tests.sh
shell
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,563
```python #!/usr/bin/env python3 """This file contains VIF element constants defined to be used by generate_vif.py""" VENDOR_NAME = "Vendor_Name" MODEL_PART_NUMBER = "Model_Part_Number" PRODUCT_REVISION = "Product_Revision" TID = "TID" VIF_PRODUCT_TYPE = "VIF_Product_Type" CERTIFICATION_TYPE = "Certification_Type" COMPONENT = "Component" USB_PD_SUPPORT = "USB_PD_Support" PD_PORT_TYPE = "PD_Port_Type" TYPE_C_STATE_MACHINE = "Type_C_State_Machine" SINK_PDO = "SnkPDO" SINK_PDO_SUPPLY_TYPE = "Snk_PDO_Supply_Type" SINK_PDO_VOLTAGE = "Snk_PDO_Voltage" SINK_PDO_OP_CURRENT = "Snk_PDO_Op_Current" SINK_PDO_OP_POWER = "Snk_PDO_Op_Power" SINK_PDO_MIN_VOLTAGE = "Snk_PDO_Min_Voltage" SINK_PDO_MAX_VOLTAGE = "Snk_PDO_Max_Voltage" PD_POWER_AS_SINK = "PD_Power_As_Sink" HIGHER_CAPABILITY_SET = "Higher_Capability_Set" FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE = "FR_Swap_Reqd_Type_C_Current_As_Initial_Source" NUM_SNK_PDOS = "Num_Snk_PDOs" ```
/content/code_sandbox/scripts/generate_usb_vif/constants/vif_element_constants.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
292
```python #!/usr/bin/env python3 """This file contains a Python script which parses through Zephyr device tree using EDT.pickle generated at build and generates a XML file containing USB VIF policies""" import argparse import inspect import os import pickle import sys import xml.etree.ElementTree as ET from constants import dt_constants from constants import other_constants from constants import pdo_constants from constants import vif_element_constants from constants import xml_constants SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..") sys.path.insert(0, os.path.join(SCRIPTS_DIR, 'dts', 'python-devicetree', 'src')) def get_value_attribute(data): if not isinstance(data, str): data = str(data) return {other_constants.VALUE: data} def get_vif_element_name(name): return xml_constants.XML_ELEMENT_NAME_PREFIX + ":" + dt_constants.DT_VIF_ELEMENTS.get( name, name) def get_root(): xml_root = ET.Element( get_vif_element_name(xml_constants.XML_ROOT_ELEMENT_NAME)) add_attributes_to_xml_element(xml_root, xml_constants.XML_NAMESPACE_ATTRIBUTES) return xml_root def add_attributes_to_xml_element(xml_ele, attributes): for key, value in attributes.items(): xml_ele.set(key, value) def add_element_to_xml(xml_ele, name, text=None, attributes=None): new_xml_ele = ET.SubElement(xml_ele, get_vif_element_name(name)) if text: new_xml_ele.text = str(text) if attributes: add_attributes_to_xml_element(new_xml_ele, attributes) return new_xml_ele def add_elements_to_xml(xml_ele, elements): for element_name in elements: text = elements[element_name].get(other_constants.TEXT, None) attributes = elements[element_name].get(other_constants.ATTRIBUTES, None) new_xml_ele = add_element_to_xml(xml_ele, element_name, text, attributes) if other_constants.CHILD in elements[element_name]: add_elements_to_xml(new_xml_ele, elements[element_name][other_constants.CHILD]) def add_vif_spec_from_source_to_xml(xml_ele, source_xml_ele): prefix = '{' + xml_constants.XML_VIF_NAMESPACE + '}' for child in source_xml_ele: element_name = child.tag[len(prefix):] if element_name in xml_constants.VIF_SPEC_ELEMENTS_FROM_SOURCE_XML: add_element_to_xml(xml_ele, element_name, child.text, child.attrib) def is_simple_datatype(value): if isinstance(value, (str, int, bool)): return True return False def get_pdo_type(pdo_value): return pdo_value >> 30 def get_xml_bool_value(value): if value: return other_constants.TRUE return other_constants.FALSE def parse_and_add_sink_pdo_to_xml(xml_ele, pdo_value, pdo_info): power_mw = 0 xml_ele = add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO) pdo_type = get_pdo_type(pdo_value) if pdo_type == pdo_constants.PDO_TYPE_FIXED: # As per USB PD specification Revision 3.1, Version 1.6, Table 6-16 Fixed supply PDO - Sink current = pdo_value & 0x3ff current_ma = current * 10 voltage = (pdo_value >> 10) & 0x3ff voltage_mv = voltage * 50 power_mw = (current_ma * voltage_mv) // 1000 if pdo_value & (1 << 28): pdo_info[vif_element_constants.HIGHER_CAPABILITY_SET] = True pdo_info[ vif_element_constants.FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE] = pdo_value & ( 3 << 23) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_VOLTAGE, f'{voltage_mv} mV', get_value_attribute(voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_OP_CURRENT, f'{current_ma} mA', get_value_attribute(current)) elif pdo_type == pdo_constants.PDO_TYPE_BATTERY: # As per USB PD specification Revision 3.1, Version 1.6, Table 6-18 Battery supply PDO - Sink max_voltage = (pdo_value >> 20) & 0x3ff max_voltage_mv = max_voltage * 50 min_voltage = (pdo_value >> 10) & 0x3ff min_voltage_mv = min_voltage * 50 power = pdo_value & 0x3ff power_mw = power * 250 add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MIN_VOLTAGE, f'{min_voltage_mv} mV', get_value_attribute(min_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MAX_VOLTAGE, f'{max_voltage_mv} mV', get_value_attribute(max_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_OP_POWER, f'{power_mw} mW', get_value_attribute(power)) elif pdo_type == pdo_constants.PDO_TYPE_VARIABLE: # As per USB PD specification Revision 3.1, Version 1.6, Table 6-17 Variable supply (non-Battery) PDO - Sink max_voltage = (pdo_value >> 20) & 0x3ff max_voltage_mv = max_voltage * 50 min_voltage = (pdo_value >> 10) & 0x3ff min_voltage_mv = min_voltage * 50 current = pdo_value & 0x3ff current_ma = current * 10 power_mw = (current_ma * max_voltage_mv) // 1000 add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MIN_VOLTAGE, f'{min_voltage_mv} mV', get_value_attribute(min_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MAX_VOLTAGE, f'{max_voltage_mv} mV', get_value_attribute(max_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_OP_CURRENT, f'{current_ma} mA', get_value_attribute(current)) elif pdo_type == pdo_constants.PDO_TYPE_AUGUMENTED: # As per USB PD specification Revision 3.1, Version 1.6, Table 6-19 Programmable Power supply APDO - Sink pps = (pdo_value >> 28) & 0x03 if pps: raise ValueError(f'ERROR: Invalid PDO_TYPE {pdo_value}') pps_max_voltage = (pdo_value >> 17) & 0xff pps_max_voltage_mv = pps_max_voltage * 100 pps_min_voltage = (pdo_value >> 8) & 0xff pps_min_voltage_mv = pps_min_voltage * 100 pps_current = pdo_value & 0x7f pps_current_ma = pps_current * 50 power_mw = (pps_current_ma * pps_max_voltage_mv) // 1000 add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MIN_VOLTAGE, f'{pps_min_voltage_mv} mV', get_value_attribute(pps_min_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_MAX_VOLTAGE, f'{pps_max_voltage_mv} mV', get_value_attribute(pps_max_voltage)) add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_OP_CURRENT, f'{pps_current_ma} mA', get_value_attribute(pps_current)) else: raise ValueError(f'ERROR: Invalid PDO_TYPE {pdo_value}') add_element_to_xml(xml_ele, vif_element_constants.SINK_PDO_SUPPLY_TYPE, pdo_constants.PDO_TYPES[pdo_type], get_value_attribute(pdo_type)) return power_mw def parse_and_add_sink_pdos_to_xml(xml_ele, sink_pdos): new_xml_ele = add_element_to_xml(xml_ele, dt_constants.SINK_PDOS) snk_max_power = 0 pdo_info = dict() for pdo_value in sink_pdos: power_mv = parse_and_add_sink_pdo_to_xml(new_xml_ele, pdo_value, pdo_info) if power_mv > snk_max_power: snk_max_power = power_mv add_element_to_xml(xml_ele, vif_element_constants.PD_POWER_AS_SINK, f'{snk_max_power} mW', get_value_attribute(snk_max_power)) add_element_to_xml(xml_ele, vif_element_constants.HIGHER_CAPABILITY_SET, None, get_value_attribute(get_xml_bool_value( vif_element_constants.HIGHER_CAPABILITY_SET in pdo_info))) fr_swap_required_type_c_current_as_initial_source = pdo_info[ vif_element_constants.FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE] add_element_to_xml(xml_ele, vif_element_constants.FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE, other_constants.FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE_VALUES[ fr_swap_required_type_c_current_as_initial_source], get_value_attribute( fr_swap_required_type_c_current_as_initial_source)) add_element_to_xml(xml_ele, vif_element_constants.NUM_SNK_PDOS, None, get_value_attribute(len(sink_pdos))) def parse_and_add_component_to_xml(xml_ele, node): add_element_to_xml(xml_ele, vif_element_constants.USB_PD_SUPPORT, None, get_value_attribute(get_xml_bool_value( not node.props[dt_constants.PD_DISABLE].val))) if not node.props[dt_constants.PD_DISABLE].val: power_role = node.props[dt_constants.POWER_ROLE].val add_element_to_xml(xml_ele, vif_element_constants.PD_PORT_TYPE, other_constants.PD_PORT_TYPE_VALUES[power_role][1], get_value_attribute( other_constants.PD_PORT_TYPE_VALUES[ power_role][0])) add_element_to_xml(xml_ele, vif_element_constants.TYPE_C_STATE_MACHINE, other_constants.TYPE_C_STATE_MACHINE_VALUES[ power_role][1], get_value_attribute( other_constants.TYPE_C_STATE_MACHINE_VALUES[ power_role][0])) if dt_constants.SINK_PDOS in node.props: parse_and_add_sink_pdos_to_xml(xml_ele, node.props[dt_constants.SINK_PDOS].val) def get_source_xml_root(source_xml_file): return ET.parse(source_xml_file).getroot() def parse_args(): parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument("--edt-pickle", required=True, help="path to read the pickled edtlib.EDT object from") parser.add_argument("--compatible", required=True, help="device tree compatible to be parsed") parser.add_argument("--vif-out", required=True, help="path to write VIF policies to") parser.add_argument("--vif-source-xml", required=True, help="XML file containing high level VIF specifications") return parser.parse_args() def main(): global edtlib args = parse_args() with open(args.edt_pickle, 'rb') as f: edt = pickle.load(f) edtlib = inspect.getmodule(edt) xml_root = get_root() source_xml_root = get_source_xml_root(args.vif_source_xml) add_elements_to_xml(xml_root, xml_constants.VIF_SPEC_ELEMENTS) add_vif_spec_from_source_to_xml(xml_root, source_xml_root) for node in edt.compat2nodes[args.compatible]: xml_ele = add_element_to_xml(xml_root, vif_element_constants.COMPONENT) parse_and_add_component_to_xml(xml_ele, node) tree = ET.ElementTree(xml_root) tree.write(args.vif_out, xml_declaration=True, encoding=xml_constants.XML_ENCODING) if __name__ == "__main__": main() ```
/content/code_sandbox/scripts/generate_usb_vif/generate_vif.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
2,596
```python #!/usr/bin/env python3 """This file contains device tree constants defined to be used by generate_vif.py""" SINK_PDOS = "sink-pdos" PD_DISABLE = "pd-disable" POWER_ROLE = "power-role" DT_VIF_ELEMENTS = { SINK_PDOS: "SnkPdoList", } ```
/content/code_sandbox/scripts/generate_usb_vif/constants/dt_constants.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
69
```python #!/usr/bin/env python3 """This file contains generic constants defined to be used by generate_vif.py""" NAME = "name" VALUE = "value" TEXT = "text" ATTRIBUTES = "attributes" CHILD = "child" TRUE = "true" FALSE = "false" PD_PORT_TYPE_VALUES = { "sink": ("0", "Consumer Only"), "source": ("3", "Provider Only"), "dual": ("4", "DRP"), } TYPE_C_STATE_MACHINE_VALUES = { "sink": ("1", "SNK"), "source": ("0", "SRC"), "dual": ("2", "DRP"), } FR_SWAP_REQD_TYPE_C_CURRENT_AS_INITIAL_SOURCE_VALUES = { 0: "FR_Swap not supported", 1: "Default USB Power", 2: "1.5A @ 5V", 3: "3A @ 5V", } ```
/content/code_sandbox/scripts/generate_usb_vif/constants/other_constants.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
202
```python #!/usr/bin/env python3 """This file contains XML constants defined to be used by generate_vif.py""" from constants import other_constants from constants import vif_element_constants XML_ENCODING = "utf-8" XML_ELEMENT_NAME_PREFIX = "vif" XML_ROOT_ELEMENT_NAME = "VIF" XML_VIF_NAMESPACE = "path_to_url" XML_NAMESPACE_ATTRIBUTES = { "xmlns:vif": XML_VIF_NAMESPACE, } VIF_SPEC_ELEMENTS = { "VIF_Specification": { other_constants.TEXT: "3.19", }, "VIF_App": { other_constants.CHILD: { "Description": { other_constants.TEXT: "This VIF XML file is generated by the Zephyr GenVIF script", } } }, } VIF_SPEC_ELEMENTS_FROM_SOURCE_XML = {vif_element_constants.VENDOR_NAME, vif_element_constants.MODEL_PART_NUMBER, vif_element_constants.PRODUCT_REVISION, vif_element_constants.TID, vif_element_constants.VIF_PRODUCT_TYPE, vif_element_constants.CERTIFICATION_TYPE, } ```
/content/code_sandbox/scripts/generate_usb_vif/constants/xml_constants.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
232
```python #!/usr/bin/env python3 """This file contains PDO constants defined to be used by generate_vif.py""" # PDO PDO_TYPE_FIXED = 0 PDO_TYPE_BATTERY = 1 PDO_TYPE_VARIABLE = 2 PDO_TYPE_AUGUMENTED = 3 PDO_TYPES = { PDO_TYPE_FIXED: "Fixed", PDO_TYPE_BATTERY: "Battery", PDO_TYPE_VARIABLE: "Variable", PDO_TYPE_AUGUMENTED: "Augmented", } ```
/content/code_sandbox/scripts/generate_usb_vif/constants/pdo_constants.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
101
```python #!/usr/bin/env python3 # # """ Log Parser for Dictionary-based Logging This uses the JSON database file to decode the input binary log data and print the log messages. """ import argparse import binascii import logging import sys import dictionary_parser from dictionary_parser.log_database import LogDatabase LOGGER_FORMAT = "%(message)s" logger = logging.getLogger("parser") LOG_HEX_SEP = "##ZLOGV1##" def parse_args(): """Parse command line arguments""" argparser = argparse.ArgumentParser(allow_abbrev=False) argparser.add_argument("dbfile", help="Dictionary Logging Database file") argparser.add_argument("logfile", help="Log Data file") argparser.add_argument("--hex", action="store_true", help="Log Data file is in hexadecimal strings") argparser.add_argument("--rawhex", action="store_true", help="Log file only contains hexadecimal log data") argparser.add_argument("--debug", action="store_true", help="Print extra debugging information") return argparser.parse_args() def read_log_file(args): """ Read the log from file """ logdata = None # Open log data file for reading if args.hex: if args.rawhex: # Simply log file with only hexadecimal data logdata = dictionary_parser.utils.convert_hex_file_to_bin(args.logfile) else: hexdata = '' with open(args.logfile, "r", encoding="iso-8859-1") as hexfile: for line in hexfile.readlines(): hexdata += line.strip() if LOG_HEX_SEP not in hexdata: logger.error("ERROR: Cannot find start of log data, exiting...") sys.exit(1) idx = hexdata.index(LOG_HEX_SEP) + len(LOG_HEX_SEP) hexdata = hexdata[idx:] if len(hexdata) % 2 != 0: # Make sure there are even number of characters idx = int(len(hexdata) / 2) * 2 hexdata = hexdata[:idx] idx = 0 while idx < len(hexdata): # When running QEMU via west or ninja, there may be additional # strings printed by QEMU, west or ninja (for example, QEMU # is terminated, or user interrupted, etc). So we need to # figure out where the end of log data stream by # trying to convert from hex to bin. idx += 2 try: binascii.unhexlify(hexdata[:idx]) except binascii.Error: idx -= 2 break logdata = binascii.unhexlify(hexdata[:idx]) else: logfile = open(args.logfile, "rb") if not logfile: logger.error("ERROR: Cannot open binary log data file: %s, exiting...", args.logfile) sys.exit(1) logdata = logfile.read() logfile.close() return logdata def main(): """Main function of log parser""" args = parse_args() # Setup logging for parser logging.basicConfig(format=LOGGER_FORMAT) if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # Read from database file database = LogDatabase.read_json_database(args.dbfile) if database is None: logger.error("ERROR: Cannot open database file: %s, exiting...", args.dbfile) sys.exit(1) logdata = read_log_file(args) if logdata is None: logger.error("ERROR: cannot read log from file: %s, exiting...", args.logfile) sys.exit(1) log_parser = dictionary_parser.get_parser(database) if log_parser is not None: logger.debug("# Build ID: %s", database.get_build_id()) logger.debug("# Target: %s, %d-bit", database.get_arch(), database.get_tgt_bits()) if database.is_tgt_little_endian(): logger.debug("# Endianness: Little") else: logger.debug("# Endianness: Big") logger.debug("# Database version: %d", database.get_version()) ret = log_parser.parse_log_data(logdata, debug=args.debug) if not ret: logger.error("ERROR: there were error(s) parsing log data") sys.exit(1) else: logger.error("ERROR: Cannot find a suitable parser matching database version!") sys.exit(1) if __name__ == "__main__": main() ```
/content/code_sandbox/scripts/logging/dictionary/log_parser.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
963
```python #!/usr/bin/env python3 # # """ Dictionary-based Logging Parser Module """ from .log_parser_v1 import LogParserV1 from .log_parser_v3 import LogParserV3 def get_parser(database): """Get the parser object based on database""" db_ver = int(database.get_version()) # DB version 1 and 2 correspond to v1 parser if db_ver in [1, 2]: return LogParserV1(database) # DB version 3 correspond to v3 parser if db_ver == 3: return LogParserV3(database) return None ```
/content/code_sandbox/scripts/logging/dictionary/dictionary_parser/__init__.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
132
```python #!/usr/bin/env python3 # # """ Utilities for Dictionary-based Logging Parser """ import binascii def convert_hex_file_to_bin(hexfile): """This converts a file in hexadecimal to binary""" bin_data = b'' with open(hexfile, "r", encoding="iso-8859-1") as hfile: for line in hfile.readlines(): hex_str = line.strip() bin_str = binascii.unhexlify(hex_str) bin_data += bin_str return bin_data def extract_one_string_in_section(section, str_ptr): """Extract one string in an ELF section""" data = section['data'] max_offset = section['size'] offset = str_ptr - section['start'] if offset < 0 or offset >= max_offset: return None ret_str = "" while (offset < max_offset) and (data[offset] != 0): ret_str += chr(data[offset]) offset += 1 return ret_str def find_string_in_mappings(string_mappings, str_ptr): """ Find string pointed by string_ptr in the string mapping list. Return None if not found. """ if string_mappings is None: return None if len(string_mappings) == 0: return None if str_ptr in string_mappings: return string_mappings[str_ptr] # No direct match on pointer value. # This may be a combined string. So check for that. for ptr, string in string_mappings.items(): if ptr <= str_ptr < (ptr + len(string)): whole_str = string_mappings[ptr] return whole_str[str_ptr - ptr:] return None ```
/content/code_sandbox/scripts/logging/dictionary/dictionary_parser/utils.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
358
```python #!/usr/bin/env python3 # # """ Abstract Class for Dictionary-based Logging Parsers """ import abc from colorama import Fore from .data_types import DataTypes LOG_LEVELS = [ ('none', Fore.WHITE), ('err', Fore.RED), ('wrn', Fore.YELLOW), ('inf', Fore.GREEN), ('dbg', Fore.BLUE) ] def get_log_level_str_color(lvl): """Convert numeric log level to string""" if lvl < 0 or lvl >= len(LOG_LEVELS): return ("unk", Fore.WHITE) return LOG_LEVELS[lvl] def formalize_fmt_string(fmt_str): """Replace unsupported formatter""" new_str = fmt_str for spec in ['d', 'i', 'o', 'u', 'x', 'X']: # Python doesn't support %ll for integer specifiers, so remove extra 'l' new_str = new_str.replace("%ll" + spec, "%l" + spec) if spec in ['x', 'X']: new_str = new_str.replace("%#ll" + spec, "%#l" + spec) # Python doesn't support %hh for integer specifiers, so remove extra 'h' new_str = new_str.replace("%hh" + spec, "%h" + spec) # No %p for pointer either, so use %x new_str = new_str.replace("%p", "0x%x") return new_str class LogParser(abc.ABC): """Abstract class of log parser""" def __init__(self, database): self.database = database self.data_types = DataTypes(self.database) @abc.abstractmethod def parse_log_data(self, logdata, debug=False): """Parse log data""" return None ```
/content/code_sandbox/scripts/logging/dictionary/dictionary_parser/log_parser.py
python
2016-05-26T17:54:19
2024-08-16T18:09:06
zephyr
zephyrproject-rtos/zephyr
10,307
380