xref: /openbmc/u-boot/tools/dtoc/fdt_util.py (revision 77b93e5e)
1#!/usr/bin/python
2#
3# Copyright (C) 2016 Google, Inc
4# Written by Simon Glass <sjg@chromium.org>
5#
6# SPDX-License-Identifier:      GPL-2.0+
7#
8
9import struct
10
11# A list of types we support
12(TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL) = range(4)
13
14def BytesToValue(bytes):
15    """Converts a string of bytes into a type and value
16
17    Args:
18        A string containing bytes
19
20    Return:
21        A tuple:
22            Type of data
23            Data, either a single element or a list of elements. Each element
24            is one of:
25                TYPE_STRING: string value from the property
26                TYPE_INT: a byte-swapped integer stored as a 4-byte string
27                TYPE_BYTE: a byte stored as a single-byte string
28    """
29    size = len(bytes)
30    strings = bytes.split('\0')
31    is_string = True
32    count = len(strings) - 1
33    if count > 0 and not strings[-1]:
34        for string in strings[:-1]:
35            if not string:
36                is_string = False
37                break
38            for ch in string:
39                if ch < ' ' or ch > '~':
40                    is_string = False
41                    break
42    else:
43        is_string = False
44    if is_string:
45        if count == 1:
46            return TYPE_STRING, strings[0]
47        else:
48            return TYPE_STRING, strings[:-1]
49    if size % 4:
50        if size == 1:
51            return TYPE_BYTE, bytes[0]
52        else:
53            return TYPE_BYTE, list(bytes)
54    val = []
55    for i in range(0, size, 4):
56        val.append(bytes[i:i + 4])
57    if size == 4:
58        return TYPE_INT, val[0]
59    else:
60        return TYPE_INT, val
61
62def GetEmpty(type):
63    """Get an empty / zero value of the given type
64
65    Returns:
66        A single value of the given type
67    """
68    if type == TYPE_BYTE:
69        return chr(0)
70    elif type == TYPE_INT:
71        return struct.pack('<I', 0);
72    elif type == TYPE_STRING:
73        return ''
74    else:
75        return True
76
77def fdt32_to_cpu(val):
78    """Convert a device tree cell to an integer
79
80    Args:
81        Value to convert (4-character string representing the cell value)
82
83    Return:
84        A native-endian integer value
85    """
86    return struct.unpack(">I", val)[0]
87