# This file was automatically generated by SWIG (https://www.swig.org).
# Version 4.4.0
#
# Do not make changes to this file unless you know what you are doing - modify
# the SWIG interface file instead.

from sys import version_info as _swig_python_version_info
# Import the low-level C/C++ module
if getattr(globals().get("__spec__"), "parent", None) or __package__ or "." in __name__:
    from . import _libfdt
else:
    import _libfdt

try:
    import builtins as __builtin__
except ImportError:
    import __builtin__

def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except __builtin__.Exception:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)


def _swig_setattr_nondynamic_instance_variable(set):
    def set_instance_attr(self, name, value):
        if name == "this":
            set(self, name, value)
        elif name == "thisown":
            self.this.own(value)
        elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
            set(self, name, value)
        else:
            raise AttributeError("You cannot add instance attributes to %s" % self)
    return set_instance_attr


def _swig_setattr_nondynamic_class_variable(set):
    def set_class_attr(cls, name, value):
        if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
            set(cls, name, value)
        else:
            raise AttributeError("You cannot add class attributes to %s" % cls)
    return set_class_attr


def _swig_add_metaclass(metaclass):
    """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
    def wrapper(cls):
        return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
    return wrapper


class _SwigNonDynamicMeta(type):
    """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
    __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)




import struct

# Error codes, corresponding to FDT_ERR_... in libfdt.h
(NOTFOUND,
        EXISTS,
        NOSPACE,
        BADOFFSET,
        BADPATH,
        BADPHANDLE,
        BADSTATE,
        TRUNCATED,
        BADMAGIC,
        BADVERSION,
        BADSTRUCTURE,
        BADLAYOUT,
        INTERNAL,
        BADNCELLS,
        BADVALUE,
        BADOVERLAY,
        NOPHANDLES) = QUIET_ALL = range(1, 18)
# QUIET_ALL can be passed as the 'quiet' parameter to avoid exceptions
# altogether. All # functions passed this value will return an error instead
# of raising an exception.

# Pass this as the 'quiet' parameter to return -ENOTFOUND on NOTFOUND errors,
# instead of raising an exception.
QUIET_NOTFOUND = (NOTFOUND,)
QUIET_NOSPACE = (NOSPACE,)


class FdtException(Exception):
    """An exception caused by an error such as one of the codes above"""
    def __init__(self, err):
        self.err = err

    def __str__(self):
        return 'pylibfdt error %d: %s' % (self.err, fdt_strerror(self.err))

def strerror(fdt_err):
    """Get the string for an error number

    Args:
        fdt_err: Error number (-ve)

    Returns:
        String containing the associated error
    """
    return fdt_strerror(fdt_err)

def check_err(val, quiet=()):
    """Raise an error if the return value is -ve

    This is used to check for errors returned by libfdt C functions.

    Args:
        val: Return value from a libfdt function
        quiet: Errors to ignore (empty to raise on all errors)

    Returns:
        val if val >= 0

    Raises
        FdtException if val < 0
    """
    if isinstance(val, int) and val < 0:
        if -val not in quiet:
            raise FdtException(val)
    return val

def check_err_null(val, quiet=()):
    """Raise an error if the return value is NULL

    This is used to check for a NULL return value from certain libfdt C
    functions

    Args:
        val: Return value from a libfdt function
        quiet: Errors to ignore (empty to raise on all errors)

    Returns:
        val if val is a list, None if not

    Raises
        FdtException if val indicates an error was reported and the error
        is not in @quiet.
    """
# Compatibility for SWIG v4.2 and earlier. SWIG 4.2 would drop the first
# item from the list if it was None, returning only the second item.
    if not isinstance(val, list):
        val = [None, val]

    if val[0] is None:
        if -val[1] not in quiet:
            raise FdtException(val[1])
    return val

class FdtRo(object):
    """Class for a read-only device-tree

    This is a base class used by FdtRw (read-write access) and FdtSw
    (sequential-write access). It implements read-only access to the
    device tree.

    Here are the three classes and when you should use them:

        FdtRo - read-only access to an existing FDT
        FdtRw - read-write access to an existing FDT (most common case)
        FdtSw - for creating a new FDT, as well as allowing read-only access
    """
    def __init__(self, data):
        self._fdt = bytearray(data)
        check_err(fdt_check_header(self._fdt));

    def as_bytearray(self):
        """Get the device tree contents as a bytearray

        This can be passed directly to libfdt functions that access a
        const void * for the device tree.

        Returns:
            bytearray containing the device tree
        """
        return bytearray(self._fdt)

    def next_node(self, nodeoffset, depth, quiet=()):
        """Find the next subnode

        Args:
            nodeoffset: Node offset of previous node
            depth: The depth of the node at nodeoffset. This is used to
                calculate the depth of the returned node
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Typle:
                Offset of the next node, if any, else a -ve error
                Depth of the returned node, if any, else undefined

        Raises:
            FdtException if no more nodes found or other error occurs
        """
        return check_err(fdt_next_node(self._fdt, nodeoffset, depth), quiet)

    def first_subnode(self, nodeoffset, quiet=()):
        """Find the first subnode of a parent node

        Args:
            nodeoffset: Node offset of parent node
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            The offset of the first subnode, if any

        Raises:
            FdtException if no subnodes found or other error occurs
        """
        return check_err(fdt_first_subnode(self._fdt, nodeoffset), quiet)

    def next_subnode(self, nodeoffset, quiet=()):
        """Find the next subnode

        Args:
            nodeoffset: Node offset of previous subnode
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            The offset of the next subnode, if any

        Raises:
            FdtException if no more subnodes found or other error occurs
        """
        return check_err(fdt_next_subnode(self._fdt, nodeoffset), quiet)

    def magic(self):
        """Return the magic word from the header

        Returns:
            Magic word
        """
        return fdt_magic(self._fdt)

    def totalsize(self):
        """Return the total size of the device tree

        Returns:
            Total tree size in bytes
        """
        return fdt_totalsize(self._fdt)

    def off_dt_struct(self):
        """Return the start of the device-tree struct area

        Returns:
            Start offset of struct area
        """
        return fdt_off_dt_struct(self._fdt)

    def off_dt_strings(self):
        """Return the start of the device-tree string area

        Returns:
            Start offset of string area
        """
        return fdt_off_dt_strings(self._fdt)

    def off_mem_rsvmap(self):
        """Return the start of the memory reserve map

        Returns:
            Start offset of memory reserve map
        """
        return fdt_off_mem_rsvmap(self._fdt)

    def version(self):
        """Return the version of the device tree

        Returns:
            Version number of the device tree
        """
        return fdt_version(self._fdt)

    def last_comp_version(self):
        """Return the last compatible version of the device tree

        Returns:
            Last compatible version number of the device tree
        """
        return fdt_last_comp_version(self._fdt)

    def boot_cpuid_phys(self):
        """Return the physical boot CPU ID

        Returns:
            Physical boot CPU ID
        """
        return fdt_boot_cpuid_phys(self._fdt)

    def size_dt_strings(self):
        """Return the start of the device-tree string area

        Returns:
            Start offset of string area
        """
        return fdt_size_dt_strings(self._fdt)

    def size_dt_struct(self):
        """Return the start of the device-tree struct area

        Returns:
            Start offset of struct area
        """
        return fdt_size_dt_struct(self._fdt)

    def num_mem_rsv(self, quiet=()):
        """Return the number of memory reserve-map records

        Returns:
            Number of memory reserve-map records
        """
        return check_err(fdt_num_mem_rsv(self._fdt), quiet)

    def get_mem_rsv(self, index, quiet=()):
        """Return the indexed memory reserve-map record

        Args:
            index: Record to return (0=first)

        Returns:
            Number of memory reserve-map records
        """
        val = fdt_get_mem_rsv(self._fdt, index)
        check_err(val[0], quiet)
        return val[1:]

    def subnode_offset(self, parentoffset, name, quiet=()):
        """Get the offset of a named subnode

        Args:
            parentoffset: Offset of the parent node to check
            name: Name of the required subnode, e.g. 'subnode@1'
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            The node offset of the found node, if any

        Raises
            FdtException if there is no node with that name, or other error
        """
        return check_err(fdt_subnode_offset(self._fdt, parentoffset, name),
                         quiet)

    def path_offset(self, path, quiet=()):
        """Get the offset for a given path

        Args:
            path: Path to the required node, e.g. '/node@3/subnode@1'
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Node offset

        Raises
            FdtException if the path is not valid or not found
        """
        return check_err(fdt_path_offset(self._fdt, path), quiet)

    def get_name(self, nodeoffset):
        """Get the name of a node

        Args:
            nodeoffset: Offset of node to check

        Returns:
            Node name

        Raises:
            FdtException on error (e.g. nodeoffset is invalid)
        """
        return check_err_null(fdt_get_name(self._fdt, nodeoffset))[0]

    def first_property_offset(self, nodeoffset, quiet=()):
        """Get the offset of the first property in a node offset

        Args:
            nodeoffset: Offset to the node to check
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Offset of the first property

        Raises
            FdtException if the associated node has no properties, or some
                other error occurred
        """
        return check_err(fdt_first_property_offset(self._fdt, nodeoffset),
                         quiet)

    def next_property_offset(self, prop_offset, quiet=()):
        """Get the next property in a node

        Args:
            prop_offset: Offset of the previous property
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Offset of the next property

        Raises:
            FdtException if the associated node has no more properties, or
                some other error occurred
        """
        return check_err(fdt_next_property_offset(self._fdt, prop_offset),
                         quiet)

    def get_property_by_offset(self, prop_offset, quiet=()):
        """Obtains a property that can be examined

        Args:
            prop_offset: Offset of property (e.g. from first_property_offset())
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Property object, or None if not found

        Raises:
            FdtException on error (e.g. invalid prop_offset or device
            tree format)
        """
        pdata = check_err_null(
                fdt_get_property_by_offset(self._fdt, prop_offset), quiet)
        if pdata[0] is None:
            return pdata[1]
        return Property(pdata[0], pdata[1])

    def getprop(self, nodeoffset, prop_name, quiet=()):
        """Get a property from a node

        Args:
            nodeoffset: Node offset containing property to get
            prop_name: Name of property to get
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Value of property as a Property object (which can be used as a
               bytearray/string), or -ve error number. On failure, returns an
               integer error

        Raises:
            FdtError if any error occurs (e.g. the property is not found)
        """
        pdata = check_err_null(fdt_getprop(self._fdt, nodeoffset, prop_name),
                               quiet)
        if pdata[0] is None:
            return pdata[1]
        return Property(prop_name, bytearray(pdata[0]))

    def hasprop(self, nodeoffset, prop_name, quiet=()):
        """Check if a node has a property

        This can be used to check boolean properties

        Args:
            nodeoffset: Node offset containing property to check
            prop_name: Name of property to check
            quiet: Errors to ignore (empty to raise on all errors). Note that
                NOTFOUND is added internally by this function so need not be
                provided

        Returns:
            True if the property exists in the node, else False. If an error
                other than -NOTFOUND is returned by fdt_getprop() then the error
                is return (-ve integer)

        Raises:
            FdtError if any error occurs other than NOTFOUND (e.g. the
                nodeoffset is invalid)
        """
        pdata = check_err_null(fdt_getprop(self._fdt, nodeoffset, prop_name),
                               quiet + (NOTFOUND,))
        if pdata[0] is None:
            if pdata[1] == -NOTFOUND:
                return False
            return pdata[1]
        return True

    def get_phandle(self, nodeoffset):
        """Get the phandle of a node

        Args:
            nodeoffset: Node offset to check

        Returns:
            phandle of node, or 0 if the node has no phandle or another error
            occurs
        """
        return fdt_get_phandle(self._fdt, nodeoffset)

    def get_alias(self, name):
        """Get the full path referenced by a given alias

        Args:
            name: name of the alias to lookup

        Returns:
            Full path to the node for the alias named 'name', if it exists
            None, if the given alias or the /aliases node does not exist
        """
        return fdt_get_alias(self._fdt, name)

    def get_path(self, nodeoffset, size_hint=1024, quiet=()):
        """Get the full path of a node

        Args:
            nodeoffset: Node offset to check
            size_hint: Hint for size of returned string

        Returns:
            Full path to the node

        Raises:
            FdtException if an error occurs
        """
        while True:
            ret, path = fdt_get_path(self._fdt, nodeoffset, size_hint)
            if ret == -NOSPACE:
                size_hint *= 2
                continue
            err = check_err(ret, quiet)
            if err:
                return err
            return path

    def parent_offset(self, nodeoffset, quiet=()):
        """Get the offset of a node's parent

        Args:
            nodeoffset: Node offset to check
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            The offset of the parent node, if any

        Raises:
            FdtException if no parent found or other error occurs
        """
        return check_err(fdt_parent_offset(self._fdt, nodeoffset), quiet)

    def node_offset_by_phandle(self, phandle, quiet=()):
        """Get the offset of a node with the given phandle

        Args:
            phandle: Phandle to search for
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            The offset of node with that phandle, if any

        Raises:
            FdtException if no node found or other error occurs
        """
        return check_err(fdt_node_offset_by_phandle(self._fdt, phandle), quiet)


class Fdt(FdtRo):
    """Device tree class, supporting all operations

    The Fdt object is created is created from a device tree binary file,
    e.g. with something like:

       fdt = Fdt(open("filename.dtb").read())

    Operations can then be performed using the methods in this class. Each
    method xxx(args...) corresponds to a libfdt function fdt_xxx(fdt, args...).

    All methods raise an FdtException if an error occurs. To avoid this
    behaviour a 'quiet' parameter is provided for some functions. This
    defaults to empty, but you can pass a list of errors that you expect.
    If one of these errors occurs, the function will return an error number
    (e.g. -NOTFOUND).
    """
    def __init__(self, data):
        FdtRo.__init__(self, data)

    @staticmethod
    def create_empty_tree(size, quiet=()):
        """Create an empty device tree ready for use

        Args:
            size: Size of device tree in bytes

        Returns:
            Fdt object containing the device tree
        """
        data = bytearray(size)
        err = check_err(fdt_create_empty_tree(data, size), quiet)
        if err:
            return err
        return Fdt(data)

    def resize(self, size, quiet=()):
        """Move the device tree into a larger or smaller space

        This creates a new device tree of size @size and moves the existing
        device tree contents over to that. It can be used to create more space
        in a device tree. Note that the Fdt object remains the same, but it
        now has a new bytearray holding the contents.

        Args:
            size: Required new size of device tree in bytes
        """
        fdt = bytearray(size)
        err = check_err(fdt_open_into(self._fdt, fdt, size), quiet)
        if err:
            return err
        self._fdt = fdt

    def pack(self, quiet=()):
        """Pack the device tree to remove unused space

        This adjusts the tree in place.

        Args:
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if any error occurs
        """
        err = check_err(fdt_pack(self._fdt), quiet)
        if err:
            return err
        del self._fdt[self.totalsize():]
        return err

    def set_name(self, nodeoffset, name, quiet=()):
        """Set the name of a node

        Args:
            nodeoffset: Node offset of node to update
            name: New node name (string without \0)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        if chr(0) in name:
            raise ValueError('Property contains embedded nul characters')
        return check_err(fdt_set_name(self._fdt, nodeoffset, name), quiet)

    def setprop(self, nodeoffset, prop_name, val, quiet=()):
        """Set the value of a property

        Args:
            nodeoffset: Node offset containing the property to create/update
            prop_name: Name of property
            val: Value to write (string or bytearray)
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name, val,
                                     len(val)), quiet)

    def setprop_bool(self, nodeoffset, prop_name, val, quiet=()):
        """Set the boolean value of a property

        Either:
            adds the property if not already present; or
            deletes the property if present

        Args:
            nodeoffset: Node offset containing the property to create/delete
            prop_name: Name of property
            val: Boolean value to write (i.e. True or False)
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        exists = self.hasprop(nodeoffset, prop_name, quiet)
        if val != exists:
            if val:
                return self.setprop(nodeoffset, prop_name, b'', quiet=quiet)
            else:
                return self.delprop(nodeoffset, prop_name, quiet=quiet)

    def setprop_u32(self, nodeoffset, prop_name, val, quiet=()):
        """Set the value of a property

        Args:
            nodeoffset: Node offset containing the property to create/update
            prop_name: Name of property
            val: Value to write (integer)
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        return check_err(fdt_setprop_u32(self._fdt, nodeoffset, prop_name, val),
                         quiet)

    def setprop_u64(self, nodeoffset, prop_name, val, quiet=()):
        """Set the value of a property

        Args:
            nodeoffset: Node offset containing the property to create/update
            prop_name: Name of property
            val: Value to write (integer)
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        return check_err(fdt_setprop_u64(self._fdt, nodeoffset, prop_name, val),
                         quiet)

    def setprop_str(self, nodeoffset, prop_name, val, quiet=()):
        """Set the string value of a property

        The property is set to the string, with a nul terminator added

        Args:
            nodeoffset: Node offset containing the property to create/update
            prop_name: Name of property
            val: Value to write (string without nul terminator). Unicode is
                supposed by encoding to UTF-8
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtException if no parent found or other error occurs
        """
        val = val.encode('utf-8') + b'\0'
        return check_err(fdt_setprop(self._fdt, nodeoffset, prop_name,
                                     val, len(val)), quiet)

    def delprop(self, nodeoffset, prop_name, quiet=()):
        """Delete a property from a node

        Args:
            nodeoffset: Node offset containing property to delete
            prop_name: Name of property to delete
            quiet: Errors to ignore (empty to raise on all errors)

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtError if the property does not exist, or another error occurs
        """
        return check_err(fdt_delprop(self._fdt, nodeoffset, prop_name), quiet)

    def add_subnode(self, parentoffset, name, quiet=()):
        """Add a new subnode to a node

        Args:
            parentoffset: Parent offset to add the subnode to
            name: Name of node to add

        Returns:
            offset of the node created, or negative error code on failure

        Raises:
            FdtError if there is not enough space, or another error occurs
        """
        return check_err(fdt_add_subnode(self._fdt, parentoffset, name), quiet)

    def del_node(self, nodeoffset, quiet=()):
        """Delete a node

        Args:
            nodeoffset: Offset of node to delete

        Returns:
            Error code, or 0 if OK

        Raises:
            FdtError if an error occurs
        """
        return check_err(fdt_del_node(self._fdt, nodeoffset), quiet)


class Property(bytearray):
    """Holds a device tree property name and value.

    This holds a copy of a property taken from the device tree. It does not
    reference the device tree, so if anything changes in the device tree,
    a Property object will remain valid.

    Properties:
        name: Property name
        value: Property value as a bytearray
    """
    def __init__(self, name, value):
        bytearray.__init__(self, value)
        self.name = name

    def as_cell(self, fmt):
        return struct.unpack('>' + fmt, self)[0]

    def as_uint32(self):
        return self.as_cell('L')

    def as_int32(self):
        return self.as_cell('l')

    def as_uint64(self):
        return self.as_cell('Q')

    def as_int64(self):
        return self.as_cell('q')

    def as_list(self, fmt):
        return list(map(lambda x: x[0], struct.iter_unpack('>' + fmt, self)))

    def as_uint32_list(self):
        return self.as_list('L')

    def as_int32_list(self):
        return self.as_list('l')

    def as_uint64_list(self):
        return self.as_list('Q')

    def as_int64_list(self):
        return self.as_list('q')

    def as_str(self):
        """Unicode is supported by decoding from UTF-8"""
        if self[-1] != 0:
            raise ValueError('Property lacks nul termination')
        if 0 in self[:-1]:
            raise ValueError('Property contains embedded nul characters')
        return self[:-1].decode('utf-8')

    def as_stringlist(self):
        """Unicode is supported by decoding from UTF-8"""
        if self[-1] != 0:
            raise ValueError('Property lacks nul termination')
        parts = self[:-1].split(b'\x00')
        return list(map(lambda x: x.decode('utf-8'), parts))


class FdtSw(FdtRo):
    """Software interface to create a device tree from scratch

    The methods in this class work by adding to an existing 'partial' device
    tree buffer of a fixed size created by instantiating this class. When the
    tree is complete, call as_fdt() to obtain a device tree ready to be used.

    Similarly with nodes, a new node is started with begin_node() and finished
    with end_node().

    The context manager functions can be used to make this a bit easier:

# First create the device tree with a node and property:
    sw = FdtSw()
    sw.finish_reservemap()
    with sw.add_node(''):
        with sw.add_node('node'):
            sw.property_u32('reg', 2)
    fdt = sw.as_fdt()

# Now we can use it as a real device tree
    fdt.setprop_u32(0, 'reg', 3)

    The size hint provides a starting size for the space to be used by the
    device tree. This will be increased automatically as needed as new items
    are added to the tree.
    """
    INC_SIZE = 1024  # Expand size by this much when out of space

    def __init__(self, size_hint=None):
        """Create a new FdtSw object

        Args:
            size_hint: A hint as to the initial size to use

        Raises:
            ValueError if size_hint is negative

        Returns:
            FdtSw object on success, else integer error code (if not raising)
        """
        if not size_hint:
            size_hint = self.INC_SIZE
        fdtsw = bytearray(size_hint)
        err = check_err(fdt_create(fdtsw, size_hint))
        if err:
            return err
        self._fdt = fdtsw

    def as_fdt(self):
        """Convert a FdtSw into an Fdt so it can be accessed as normal

        Creates a new Fdt object from the work-in-progress device tree. This
        does not call fdt_finish() on the current object, so it is possible to
        add more nodes/properties and call as_fdt() again to get an updated
        tree.

        Returns:
            Fdt object allowing access to the newly created device tree
        """
        fdtsw = bytearray(self._fdt)
        check_err(fdt_finish(fdtsw))
        return Fdt(fdtsw)

    def check_space(self, val):
        """Check if we need to add more space to the FDT

        This should be called with the error code from an operation. If this is
        -NOSPACE then the FDT will be expanded to have more space, and True will
        be returned, indicating that the operation needs to be tried again.

        Args:
            val: Return value from the operation that was attempted

        Returns:
            True if the operation must be retried, else False
        """
        if check_err(val, QUIET_NOSPACE) < 0:
            self.resize(len(self._fdt) + self.INC_SIZE)
            return True
        return False

    def resize(self, size):
        """Resize the buffer to accommodate a larger tree

        Args:
            size: New size of tree

        Raises:
            FdtException on any error
        """
        fdt = bytearray(size)
        err = check_err(fdt_resize(self._fdt, fdt, size))
        self._fdt = fdt

    def add_reservemap_entry(self, addr, size):
        """Add a new memory reserve map entry

        Once finished adding, you must call finish_reservemap().

        Args:
            addr: 64-bit start address
            size: 64-bit size

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_add_reservemap_entry(self._fdt, addr,
                                                        size)):
            pass

    def finish_reservemap(self):
        """Indicate that there are no more reserve map entries to add

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_finish_reservemap(self._fdt)):
            pass

    def begin_node(self, name):
        """Begin a new node

        Use this before adding properties to the node. Then call end_node() to
        finish it. You can also use the context manager as shown in the FdtSw
        class comment.

        Args:
            name: Name of node to begin

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_begin_node(self._fdt, name)):
            pass

    def property_string(self, name, string):
        """Add a property with a string value

        The string will be nul-terminated when written to the device tree

        Args:
            name: Name of property to add
            string: String value of property

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_property_string(self._fdt, name, string)):
            pass

    def property_u32(self, name, val):
        """Add a property with a 32-bit value

        Write a single-cell value to the device tree

        Args:
            name: Name of property to add
            val: Value of property

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_property_u32(self._fdt, name, val)):
            pass

    def property_u64(self, name, val):
        """Add a property with a 64-bit value

        Write a double-cell value to the device tree in big-endian format

        Args:
            name: Name of property to add
            val: Value of property

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_property_u64(self._fdt, name, val)):
            pass

    def property_cell(self, name, val):
        """Add a property with a single-cell value

        Write a single-cell value to the device tree

        Args:
            name: Name of property to add
            val: Value of property
            quiet: Errors to ignore (empty to raise on all errors)

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_property_cell(self._fdt, name, val)):
            pass

    def property(self, name, val):
        """Add a property

        Write a new property with the given value to the device tree. The value
        is taken as is and is not nul-terminated

        Args:
            name: Name of property to add
            val: Value of property (bytes)
            quiet: Errors to ignore (empty to raise on all errors)

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_property_stub(self._fdt, name, val,
                                                 len(val))):
            pass

    def end_node(self):
        """End a node

        Use this after adding properties to a node to close it off. You can also
        use the context manager as shown in the FdtSw class comment.

        Args:
            quiet: Errors to ignore (empty to raise on all errors)

        Raises:
            FdtException on any error
        """
        while self.check_space(fdt_end_node(self._fdt)):
            pass

    def add_node(self, name):
        """Create a new context for adding a node

        When used in a 'with' clause this starts a new node and finishes it
        afterward.

        Args:
            name: Name of node to add
        """
        return NodeAdder(self, name)


class NodeAdder():
    """Class to provide a node context

    This allows you to add nodes in a more natural way:

        with fdtsw.add_node('name'):
            fdtsw.property_string('test', 'value')

    The node is automatically completed with a call to end_node() when the
    context exits.
    """
    def __init__(self, fdtsw, name):
        self._fdt = fdtsw
        self._name = name

    def __enter__(self):
        self._fdt.begin_node(self._name)

    def __exit__(self, type, value, traceback):
        self._fdt.end_node()

class fdt_header(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr
    magic = property(_libfdt.fdt_header_magic_get, _libfdt.fdt_header_magic_set)
    totalsize = property(_libfdt.fdt_header_totalsize_get, _libfdt.fdt_header_totalsize_set)
    off_dt_struct = property(_libfdt.fdt_header_off_dt_struct_get, _libfdt.fdt_header_off_dt_struct_set)
    off_dt_strings = property(_libfdt.fdt_header_off_dt_strings_get, _libfdt.fdt_header_off_dt_strings_set)
    off_mem_rsvmap = property(_libfdt.fdt_header_off_mem_rsvmap_get, _libfdt.fdt_header_off_mem_rsvmap_set)
    version = property(_libfdt.fdt_header_version_get, _libfdt.fdt_header_version_set)
    last_comp_version = property(_libfdt.fdt_header_last_comp_version_get, _libfdt.fdt_header_last_comp_version_set)
    boot_cpuid_phys = property(_libfdt.fdt_header_boot_cpuid_phys_get, _libfdt.fdt_header_boot_cpuid_phys_set)
    size_dt_strings = property(_libfdt.fdt_header_size_dt_strings_get, _libfdt.fdt_header_size_dt_strings_set)
    size_dt_struct = property(_libfdt.fdt_header_size_dt_struct_get, _libfdt.fdt_header_size_dt_struct_set)

    def __init__(self):
        _libfdt.fdt_header_swiginit(self, _libfdt.new_fdt_header())
    __swig_destroy__ = _libfdt.delete_fdt_header

# Register fdt_header in _libfdt:
_libfdt.fdt_header_swigregister(fdt_header)
class fdt_reserve_entry(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr
    address = property(_libfdt.fdt_reserve_entry_address_get, _libfdt.fdt_reserve_entry_address_set)
    size = property(_libfdt.fdt_reserve_entry_size_get, _libfdt.fdt_reserve_entry_size_set)

    def __init__(self):
        _libfdt.fdt_reserve_entry_swiginit(self, _libfdt.new_fdt_reserve_entry())
    __swig_destroy__ = _libfdt.delete_fdt_reserve_entry

# Register fdt_reserve_entry in _libfdt:
_libfdt.fdt_reserve_entry_swigregister(fdt_reserve_entry)
class fdt_node_header(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr
    tag = property(_libfdt.fdt_node_header_tag_get, _libfdt.fdt_node_header_tag_set)
    name = property(_libfdt.fdt_node_header_name_get)

    def __init__(self):
        _libfdt.fdt_node_header_swiginit(self, _libfdt.new_fdt_node_header())
    __swig_destroy__ = _libfdt.delete_fdt_node_header

# Register fdt_node_header in _libfdt:
_libfdt.fdt_node_header_swigregister(fdt_node_header)
class fdt_property(object):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr
    tag = property(_libfdt.fdt_property_tag_get, _libfdt.fdt_property_tag_set)
    len = property(_libfdt.fdt_property_len_get, _libfdt.fdt_property_len_set)
    nameoff = property(_libfdt.fdt_property_nameoff_get, _libfdt.fdt_property_nameoff_set)
    data = property(_libfdt.fdt_property_data_get)

    def __init__(self):
        _libfdt.fdt_property_swiginit(self, _libfdt.new_fdt_property())
    __swig_destroy__ = _libfdt.delete_fdt_property

# Register fdt_property in _libfdt:
_libfdt.fdt_property_swigregister(fdt_property)
FDT_MAGIC = _libfdt.FDT_MAGIC
FDT_BEGIN_NODE = _libfdt.FDT_BEGIN_NODE
FDT_END_NODE = _libfdt.FDT_END_NODE
FDT_PROP = _libfdt.FDT_PROP
FDT_NOP = _libfdt.FDT_NOP
FDT_END = _libfdt.FDT_END

def fdt_get_path(fdt, nodeoffset, buf):
    return _libfdt.fdt_get_path(fdt, nodeoffset, buf)

def fdt_magic(fdt):
    return _libfdt.fdt_magic(fdt)

def fdt_totalsize(fdt):
    return _libfdt.fdt_totalsize(fdt)

def fdt_off_dt_struct(fdt):
    return _libfdt.fdt_off_dt_struct(fdt)

def fdt_off_dt_strings(fdt):
    return _libfdt.fdt_off_dt_strings(fdt)

def fdt_off_mem_rsvmap(fdt):
    return _libfdt.fdt_off_mem_rsvmap(fdt)

def fdt_version(fdt):
    return _libfdt.fdt_version(fdt)

def fdt_last_comp_version(fdt):
    return _libfdt.fdt_last_comp_version(fdt)

def fdt_boot_cpuid_phys(fdt):
    return _libfdt.fdt_boot_cpuid_phys(fdt)

def fdt_size_dt_strings(fdt):
    return _libfdt.fdt_size_dt_strings(fdt)

def fdt_size_dt_struct(fdt):
    return _libfdt.fdt_size_dt_struct(fdt)

def fdt_property_string(fdt, name, val):
    return _libfdt.fdt_property_string(fdt, name, val)

def fdt_property_cell(fdt, name, val):
    return _libfdt.fdt_property_cell(fdt, name, val)

def fdt_property_stub(fdt, name, val, len):
    return _libfdt.fdt_property_stub(fdt, name, val, len)
FDT_FIRST_SUPPORTED_VERSION = _libfdt.FDT_FIRST_SUPPORTED_VERSION
FDT_LAST_COMPATIBLE_VERSION = _libfdt.FDT_LAST_COMPATIBLE_VERSION
FDT_LAST_SUPPORTED_VERSION = _libfdt.FDT_LAST_SUPPORTED_VERSION
FDT_ERR_NOTFOUND = _libfdt.FDT_ERR_NOTFOUND
FDT_ERR_EXISTS = _libfdt.FDT_ERR_EXISTS
FDT_ERR_NOSPACE = _libfdt.FDT_ERR_NOSPACE
FDT_ERR_BADOFFSET = _libfdt.FDT_ERR_BADOFFSET
FDT_ERR_BADPATH = _libfdt.FDT_ERR_BADPATH
FDT_ERR_BADPHANDLE = _libfdt.FDT_ERR_BADPHANDLE
FDT_ERR_BADSTATE = _libfdt.FDT_ERR_BADSTATE
FDT_ERR_TRUNCATED = _libfdt.FDT_ERR_TRUNCATED
FDT_ERR_BADMAGIC = _libfdt.FDT_ERR_BADMAGIC
FDT_ERR_BADVERSION = _libfdt.FDT_ERR_BADVERSION
FDT_ERR_BADSTRUCTURE = _libfdt.FDT_ERR_BADSTRUCTURE
FDT_ERR_BADLAYOUT = _libfdt.FDT_ERR_BADLAYOUT
FDT_ERR_INTERNAL = _libfdt.FDT_ERR_INTERNAL
FDT_ERR_BADNCELLS = _libfdt.FDT_ERR_BADNCELLS
FDT_ERR_BADVALUE = _libfdt.FDT_ERR_BADVALUE
FDT_ERR_BADOVERLAY = _libfdt.FDT_ERR_BADOVERLAY
FDT_ERR_NOPHANDLES = _libfdt.FDT_ERR_NOPHANDLES
FDT_ERR_BADFLAGS = _libfdt.FDT_ERR_BADFLAGS
FDT_ERR_ALIGNMENT = _libfdt.FDT_ERR_ALIGNMENT
FDT_ERR_MAX = _libfdt.FDT_ERR_MAX
FDT_MAX_PHANDLE = _libfdt.FDT_MAX_PHANDLE

def fdt_offset_ptr_w(fdt, offset, checklen):
    return _libfdt.fdt_offset_ptr_w(fdt, offset, checklen)

def fdt_next_tag(fdt, offset, nextoffset):
    return _libfdt.fdt_next_tag(fdt, offset, nextoffset)

def fdt16_ld(p):
    return _libfdt.fdt16_ld(p)

def fdt32_ld(p):
    return _libfdt.fdt32_ld(p)

def fdt32_st(property, value):
    return _libfdt.fdt32_st(property, value)

def fdt64_ld(p):
    return _libfdt.fdt64_ld(p)

def fdt64_st(property, value):
    return _libfdt.fdt64_st(property, value)

def fdt_next_node(fdt, offset, depth):
    return _libfdt.fdt_next_node(fdt, offset, depth)

def fdt_first_subnode(fdt, offset):
    return _libfdt.fdt_first_subnode(fdt, offset)

def fdt_next_subnode(fdt, offset):
    return _libfdt.fdt_next_subnode(fdt, offset)

def fdt_set_magic(fdt, val):
    return _libfdt.fdt_set_magic(fdt, val)

def fdt_set_totalsize(fdt, val):
    return _libfdt.fdt_set_totalsize(fdt, val)

def fdt_set_off_dt_struct(fdt, val):
    return _libfdt.fdt_set_off_dt_struct(fdt, val)

def fdt_set_off_dt_strings(fdt, val):
    return _libfdt.fdt_set_off_dt_strings(fdt, val)

def fdt_set_off_mem_rsvmap(fdt, val):
    return _libfdt.fdt_set_off_mem_rsvmap(fdt, val)

def fdt_set_version(fdt, val):
    return _libfdt.fdt_set_version(fdt, val)

def fdt_set_last_comp_version(fdt, val):
    return _libfdt.fdt_set_last_comp_version(fdt, val)

def fdt_set_boot_cpuid_phys(fdt, val):
    return _libfdt.fdt_set_boot_cpuid_phys(fdt, val)

def fdt_set_size_dt_strings(fdt, val):
    return _libfdt.fdt_set_size_dt_strings(fdt, val)

def fdt_set_size_dt_struct(fdt, val):
    return _libfdt.fdt_set_size_dt_struct(fdt, val)

def fdt_header_size(fdt):
    return _libfdt.fdt_header_size(fdt)

def fdt_header_size_(version):
    return _libfdt.fdt_header_size_(version)

def fdt_check_header(fdt):
    return _libfdt.fdt_check_header(fdt)

def fdt_move(fdt, buf, bufsize):
    return _libfdt.fdt_move(fdt, buf, bufsize)

def fdt_check_full(fdt, bufsize):
    return _libfdt.fdt_check_full(fdt, bufsize)

def fdt_get_string(fdt, stroffset):
    return _libfdt.fdt_get_string(fdt, stroffset)

def fdt_string(fdt, stroffset):
    return _libfdt.fdt_string(fdt, stroffset)

def fdt_find_max_phandle(fdt, phandle):
    return _libfdt.fdt_find_max_phandle(fdt, phandle)

def fdt_get_max_phandle(fdt):
    return _libfdt.fdt_get_max_phandle(fdt)

def fdt_generate_phandle(fdt, phandle):
    return _libfdt.fdt_generate_phandle(fdt, phandle)

def fdt_num_mem_rsv(fdt):
    return _libfdt.fdt_num_mem_rsv(fdt)

def fdt_get_mem_rsv(fdt, n):
    return _libfdt.fdt_get_mem_rsv(fdt, n)

def fdt_subnode_offset(fdt, parentoffset, name):
    return _libfdt.fdt_subnode_offset(fdt, parentoffset, name)

def fdt_path_offset(fdt, path):
    return _libfdt.fdt_path_offset(fdt, path)

def fdt_get_name(fdt, nodeoffset):
    return _libfdt.fdt_get_name(fdt, nodeoffset)

def fdt_first_property_offset(fdt, nodeoffset):
    return _libfdt.fdt_first_property_offset(fdt, nodeoffset)

def fdt_next_property_offset(fdt, offset):
    return _libfdt.fdt_next_property_offset(fdt, offset)

def fdt_get_property_by_offset(fdt, offset):
    return _libfdt.fdt_get_property_by_offset(fdt, offset)

def fdt_get_property_by_offset_w(fdt, offset):
    return _libfdt.fdt_get_property_by_offset_w(fdt, offset)

def fdt_get_property(fdt, nodeoffset, name):
    return _libfdt.fdt_get_property(fdt, nodeoffset, name)

def fdt_get_property_w(fdt, nodeoffset, name):
    return _libfdt.fdt_get_property_w(fdt, nodeoffset, name)

def fdt_getprop(fdt, nodeoffset, name):
    return _libfdt.fdt_getprop(fdt, nodeoffset, name)

def fdt_getprop_w(fdt, nodeoffset, name):
    return _libfdt.fdt_getprop_w(fdt, nodeoffset, name)

def fdt_get_phandle(fdt, nodeoffset):
    return _libfdt.fdt_get_phandle(fdt, nodeoffset)

def fdt_get_alias(fdt, name):
    return _libfdt.fdt_get_alias(fdt, name)

def fdt_get_symbol(fdt, name):
    return _libfdt.fdt_get_symbol(fdt, name)

def fdt_supernode_atdepth_offset(fdt, nodeoffset, supernodedepth, nodedepth):
    return _libfdt.fdt_supernode_atdepth_offset(fdt, nodeoffset, supernodedepth, nodedepth)

def fdt_node_depth(fdt, nodeoffset):
    return _libfdt.fdt_node_depth(fdt, nodeoffset)

def fdt_parent_offset(fdt, nodeoffset):
    return _libfdt.fdt_parent_offset(fdt, nodeoffset)

def fdt_node_offset_by_prop_value(fdt, startoffset, propname, propval, proplen):
    return _libfdt.fdt_node_offset_by_prop_value(fdt, startoffset, propname, propval, proplen)

def fdt_node_offset_by_phandle(fdt, phandle):
    return _libfdt.fdt_node_offset_by_phandle(fdt, phandle)

def fdt_node_check_compatible(fdt, nodeoffset, compatible):
    return _libfdt.fdt_node_check_compatible(fdt, nodeoffset, compatible)

def fdt_node_offset_by_compatible(fdt, startoffset, compatible):
    return _libfdt.fdt_node_offset_by_compatible(fdt, startoffset, compatible)

def fdt_stringlist_contains(strlist, listlen, str):
    return _libfdt.fdt_stringlist_contains(strlist, listlen, str)

def fdt_stringlist_count(fdt, nodeoffset, property):
    return _libfdt.fdt_stringlist_count(fdt, nodeoffset, property)

def fdt_stringlist_search(fdt, nodeoffset, property, string):
    return _libfdt.fdt_stringlist_search(fdt, nodeoffset, property, string)

def fdt_stringlist_get(fdt, nodeoffset, property, index):
    return _libfdt.fdt_stringlist_get(fdt, nodeoffset, property, index)
FDT_MAX_NCELLS = _libfdt.FDT_MAX_NCELLS

def fdt_address_cells(fdt, nodeoffset):
    return _libfdt.fdt_address_cells(fdt, nodeoffset)

def fdt_size_cells(fdt, nodeoffset):
    return _libfdt.fdt_size_cells(fdt, nodeoffset)

def fdt_setprop_inplace_u32(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_inplace_u32(fdt, nodeoffset, name, val)

def fdt_setprop_inplace_u64(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_inplace_u64(fdt, nodeoffset, name, val)

def fdt_setprop_inplace_cell(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_inplace_cell(fdt, nodeoffset, name, val)

def fdt_nop_property(fdt, nodeoffset, name):
    return _libfdt.fdt_nop_property(fdt, nodeoffset, name)

def fdt_nop_node(fdt, nodeoffset):
    return _libfdt.fdt_nop_node(fdt, nodeoffset)
FDT_CREATE_FLAG_NO_NAME_DEDUP = _libfdt.FDT_CREATE_FLAG_NO_NAME_DEDUP
FDT_CREATE_FLAGS_ALL = _libfdt.FDT_CREATE_FLAGS_ALL

def fdt_create_with_flags(buf, bufsize, flags):
    return _libfdt.fdt_create_with_flags(buf, bufsize, flags)

def fdt_create(buf, bufsize):
    return _libfdt.fdt_create(buf, bufsize)

def fdt_resize(fdt, buf, bufsize):
    return _libfdt.fdt_resize(fdt, buf, bufsize)

def fdt_add_reservemap_entry(fdt, addr, size):
    return _libfdt.fdt_add_reservemap_entry(fdt, addr, size)

def fdt_finish_reservemap(fdt):
    return _libfdt.fdt_finish_reservemap(fdt)

def fdt_begin_node(fdt, name):
    return _libfdt.fdt_begin_node(fdt, name)

def fdt_property_u32(fdt, name, val):
    return _libfdt.fdt_property_u32(fdt, name, val)

def fdt_property_u64(fdt, name, val):
    return _libfdt.fdt_property_u64(fdt, name, val)

def fdt_property_placeholder(fdt, name, len, valp):
    return _libfdt.fdt_property_placeholder(fdt, name, len, valp)

def fdt_end_node(fdt):
    return _libfdt.fdt_end_node(fdt)

def fdt_finish(fdt):
    return _libfdt.fdt_finish(fdt)

def fdt_create_empty_tree(buf, bufsize):
    return _libfdt.fdt_create_empty_tree(buf, bufsize)

def fdt_open_into(fdt, buf, bufsize):
    return _libfdt.fdt_open_into(fdt, buf, bufsize)

def fdt_pack(fdt):
    return _libfdt.fdt_pack(fdt)

def fdt_add_mem_rsv(fdt, address, size):
    return _libfdt.fdt_add_mem_rsv(fdt, address, size)

def fdt_del_mem_rsv(fdt, n):
    return _libfdt.fdt_del_mem_rsv(fdt, n)

def fdt_set_name(fdt, nodeoffset, name):
    return _libfdt.fdt_set_name(fdt, nodeoffset, name)

def fdt_setprop(fdt, nodeoffset, name, val, len):
    return _libfdt.fdt_setprop(fdt, nodeoffset, name, val, len)

def fdt_setprop_placeholder(fdt, nodeoffset, name, len, prop_data):
    return _libfdt.fdt_setprop_placeholder(fdt, nodeoffset, name, len, prop_data)

def fdt_setprop_u32(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_u32(fdt, nodeoffset, name, val)

def fdt_setprop_u64(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_u64(fdt, nodeoffset, name, val)

def fdt_setprop_cell(fdt, nodeoffset, name, val):
    return _libfdt.fdt_setprop_cell(fdt, nodeoffset, name, val)

def fdt_appendprop(fdt, nodeoffset, name, val, len):
    return _libfdt.fdt_appendprop(fdt, nodeoffset, name, val, len)

def fdt_appendprop_u32(fdt, nodeoffset, name, val):
    return _libfdt.fdt_appendprop_u32(fdt, nodeoffset, name, val)

def fdt_appendprop_u64(fdt, nodeoffset, name, val):
    return _libfdt.fdt_appendprop_u64(fdt, nodeoffset, name, val)

def fdt_appendprop_cell(fdt, nodeoffset, name, val):
    return _libfdt.fdt_appendprop_cell(fdt, nodeoffset, name, val)

def fdt_appendprop_addrrange(fdt, parent, nodeoffset, name, addr, size):
    return _libfdt.fdt_appendprop_addrrange(fdt, parent, nodeoffset, name, addr, size)

def fdt_delprop(fdt, nodeoffset, name):
    return _libfdt.fdt_delprop(fdt, nodeoffset, name)

def fdt_add_subnode(fdt, parentoffset, name):
    return _libfdt.fdt_add_subnode(fdt, parentoffset, name)

def fdt_del_node(fdt, nodeoffset):
    return _libfdt.fdt_del_node(fdt, nodeoffset)

def fdt_overlay_apply(fdt, fdto):
    return _libfdt.fdt_overlay_apply(fdt, fdto)

def fdt_overlay_target_offset(fdt, fdto, fragment_offset, pathp):
    return _libfdt.fdt_overlay_target_offset(fdt, fdto, fragment_offset, pathp)

def fdt_strerror(errval):
    return _libfdt.fdt_strerror(errval)

