Skip to contentSkip to conversation

binman: Add more tests and support for updating the device tree

PATCH Superseded Simon Glass 1 participant 30 messages Jun 6, 2018 Device tree

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover binman: Add more tests and support for updating the device tree

At present we have 100% code coverage for binman. This series adds the same for dtoc (which converts device-tree data to C) and the Fdt class (which provides convenient Python access to the device tree).

Binman already support writing a map file showing the location of each entry in the images in produces. But, with the exception of automatic linker symbols in SPL, this information is not available to U-Boot itself. The series adds support for this, by writing the updated entry position and size back to the device tree for inclusion in the image. With this, U-Boot can easily read this information and locate image entries at runtime.

Note: At present the access to device-tree values is more clumbsy than it could be. Once pylibfdt support is finished, this needs another look.

Simon Glass (28):
binman: Make the operation of Entry__testing explicit
binman: Tidy up variables in _RunMicrocodeTest()
binman: Correct operation of ObtainContents()
binman: Tidy up execution of tests
binman: Tidy up setting of entry contents
libfdt: Bring in proposed pylibfdt changes
libfdt: Fix the Python pack() function
libfdt: Add get_property() and del_node()
binman: Move coverage logic into a new test_util file
dtoc: Add some tests for the fdt module
dtoc: Update tests to write failures to /tmp
dtoc: Update fdt tests to increase code coverage
dtoc: Make use of the new pylibfdt methods
dtoc: Drop use of a local dtb buffer
dtoc: Keep track of property offsets
dtoc: Fix Fdt.GetNode() to handle a missing node
dtoc: Update fdt tests to increase code coverage
dtoc: Fix properties with a single zero-arg phandle
dtoc: Fix some minor errors
dtoc: Add a test for code coverage
dtoc: Increase code coverage to 100%
binman: Move capture_sys_output() to test_util
dtoc: Avoid unwanted output during tests
dtoc: Add functions to add integer properties
binman: Complete documentation of stages
binman: Add a ProcessFdt() method
binman: Add a SetCalculatedProperties() method
binman: Support updating the device tree with calc'd info

Tom Rini (1):
binman: Switch to 'python-coverage'

 scripts/dtc/libfdt/libfdt.h                   |   3 +
 scripts/dtc/pylibfdt/libfdt.i_shipped         | 725 ++++++++++++++++--
 tools/binman/README                           |  45 +-
 tools/binman/binman.py                        |  38 +-
 tools/binman/bsection.py                      |  27 +
 tools/binman/cmdline.py                       |   2 +
 tools/binman/control.py                       |  58 +-
 tools/binman/elf_test.py                      |  22 +-
 tools/binman/entry.py                         |  42 +
 tools/binman/etype/_testing.py                |  27 +-
 tools/binman/etype/blob.py                    |   3 +-
 tools/binman/etype/section.py                 |  13 +-
 tools/binman/etype/u_boot_dtb_with_ucode.py   |  47 +-
 tools/binman/etype/u_boot_spl_bss_pad.py      |   4 +-
 tools/binman/etype/u_boot_ucode.py            |   9 +-
 tools/binman/etype/u_boot_with_ucode_ptr.py   |  11 +-
 tools/binman/ftest.py                         | 151 +++-
 tools/binman/image.py                         |  17 +
 tools/binman/image_test.py                    |   2 +-
 tools/binman/test/41_unknown_pos_size.dts     |   1 +
 tools/binman/test/57_unknown_contents.dts     |  14 +
 .../test/58_x86_ucode_spl_needs_retry.dts     |  36 +
 tools/binman/test/59_change_size.dts          |  14 +
 tools/binman/test/60_fdt_update.dts           |  28 +
 tools/dtoc/dtb_platdata.py                    |  15 +-
 tools/dtoc/dtoc.py                            |  35 +-
 tools/dtoc/dtoc_test_add_prop.dts             |  24 +
 tools/dtoc/dtoc_test_addr32_64.dts            |   2 +-
 tools/dtoc/dtoc_test_addr64_32.dts            |   2 +-
 tools/dtoc/dtoc_test_bad_reg.dts              |  17 +
 tools/dtoc/dtoc_test_bad_reg2.dts             |  17 +
 tools/dtoc/dtoc_test_phandle.dts              |   6 +
 tools/dtoc/dtoc_test_phandle_bad.dts          |  16 +
 tools/dtoc/dtoc_test_phandle_bad2.dts         |  22 +
 tools/dtoc/dtoc_test_phandle_reorder.dts      |  23 +
 tools/dtoc/dtoc_test_phandle_single.dts       |  23 +
 tools/dtoc/dtoc_test_simple.dts               |   1 +
 tools/dtoc/fdt.py                             | 110 ++-
 tools/dtoc/fdt_util.py                        |   4 +-
 tools/dtoc/test_dtoc.py                       | 223 +++++-
 tools/dtoc/test_fdt                           |   1 +
 tools/dtoc/test_fdt.py                        | 390 ++++++++++
 tools/patman/test_util.py                     |  73 ++
 43 files changed, 2097 insertions(+), 246 deletions(-)
 create mode 100644 tools/binman/test/57_unknown_contents.dts
 create mode 100644 tools/binman/test/58_x86_ucode_spl_needs_retry.dts
 create mode 100644 tools/binman/test/59_change_size.dts
 create mode 100644 tools/binman/test/60_fdt_update.dts
 create mode 100644 tools/dtoc/dtoc_test_add_prop.dts
 create mode 100644 tools/dtoc/dtoc_test_bad_reg.dts
 create mode 100644 tools/dtoc/dtoc_test_bad_reg2.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_bad.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_bad2.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_reorder.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_single.dts
 create mode 120000 tools/dtoc/test_fdt
 create mode 100755 tools/dtoc/test_fdt.py
 create mode 100644 tools/patman/test_util.py
Signature · 6 lines
2.17.1.1185.g55be947832-goog

_______________________________________________
U-Boot mailing list
[email protected]
https://lists.denx.de/listinfo/u-boot
#1 lore raw

PATCH 1/29 binman: Switch to 'python-coverage'

From: Tom Rini <[email protected]>

The most portable way to get access to coverage is to invoke it as 'python-coverage'.

---

 tools/binman/README    | 3 +--
 tools/binman/binman.py | 4 ++--
 2 files changed, 3 insertions(+), 4 deletions(-)
tools/binman/README +1 -2
index 22f21bc5b44..f74e39242f6 100644
@@ -583,8 +583,7 @@ implementations target 100% test coverage. Run 'binman -T' to check this.
 
 To enable Python test coverage on Debian-type distributions (e.g. Ubuntu):
 
-   $ sudo apt-get install python-pip python-pytest
-   $ sudo pip install coverage
+   $ sudo apt-get install python-coverage python-pytest
 
 
 Advanced Features / Technical docs
tools/binman/binman.py +2 -2
index 31b045337d2..f3044ca2124 100755
@@ -81,11 +81,11 @@ def RunTests(debug, args):
 def RunTestCoverage():
     """Run the tests and check that we get 100% coverage"""
     # This uses the build output from sandbox_spl to get _libfdt.so
-    cmd = ('PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools coverage run '
+    cmd = ('PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools python-coverage run '
             '--include "tools/binman/*.py" --omit "*test*,*binman.py" '
             'tools/binman/binman.py -t' % options.build_dir)
     os.system(cmd)
-    stdout = command.Output('coverage', 'report')
+    stdout = command.Output('python-coverage', 'report')
     lines = stdout.splitlines()
 
     test_set= set([os.path.basename(line.split()[0])
Signature · 1 line
2.17.1.1185.g55be947832-goog
#2 lore raw

PATCH 2/29 binman: Make the operation of Entry__testing explicit

In reply to Simon Glass

This fake entry is used for testing. At present it only has one behaviour which is to return an invalid set of entry positions, to cause an error.

The fake entry will need to be used for other things too. Allow the test .dts file to specify the behaviour of the fake entry, so we can control its behaviour easily.

While we are here, drop the ReadContents() method, since this only applies to subclasses of Entry_blob, which Entry__testing is not.

---

 tools/binman/etype/_testing.py            | 14 ++++++++++----
 tools/binman/test/41_unknown_pos_size.dts |  1 +
 2 files changed, 11 insertions(+), 4 deletions(-)
tools/binman/etype/_testing.py +10 -4
index c376dd5c9ca..0b1eaefc3ce 100644
@@ -10,16 +10,22 @@ import fdt_util
 import tools
 
 class Entry__testing(Entry):
+    """A fake entry used for testing
+
+    Properties:
+        return_invalid_entry: Return an invalid entry from GetPositions()
+    """
     def __init__(self, section, etype, node):
         Entry.__init__(self, section, etype, node)
+        self.return_invalid_entry = fdt_util.GetBool(self._node,
+                                                     'return-invalid-entry')
 
     def ObtainContents(self):
         self.data = 'a'
         self.contents_size = len(self.data)
         return True
 
-    def ReadContents(self):
-        return True
-
     def GetPositions(self):
-        return {'invalid-entry': [1, 2]}
+        if self.return_invalid_entry :
+            return {'invalid-entry': [1, 2]}
+        return {}
tools/binman/test/41_unknown_pos_size.dts +1 -0
index a8e7d8aa227..94fe821c470 100644
@@ -6,6 +6,7 @@
 
 	binman {
 		_testing {
+			return-invalid-entry;
 		};
         };
 };
Signature · 1 line
2.17.1.1185.g55be947832-goog
#3 lore raw

PATCH 3/29 binman: Tidy up variables in _RunMicrocodeTest()

In reply to Simon Glass

At present we call the three entries first, second and third. Rename them to reflect their contents instead, for clarity.

---

 tools/binman/ftest.py | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)
tools/binman/ftest.py +18 -7
index eb8a0793cbe..80eadeffab8 100644
@@ -689,29 +689,40 @@ class TestFunctional(unittest.TestCase):
         self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
 
     def _RunMicrocodeTest(self, dts_fname, nodtb_data):
+        """Handle running a test for insertion of microcode
+
+        Args:
+            dts_fname: Name of test .dts file
+            nodtb_data: Data that we expect in the first section
+
+        Returns:
+            Tuple:
+                Contents of first region (U-Boot or SPL)
+                Position and size components of microcode pointer, as inserted
+                    in the above (two 4-byte words)
+        """
         data = self._DoReadFile(dts_fname, True)
 
         # Now check the device tree has no microcode
-        second = data[len(nodtb_data):]
+        dtb_with_ucode = data[len(nodtb_data):]
+        fdt_len = self.GetFdtLen(dtb_with_ucode)
+        ucode_content = dtb_with_ucode[fdt_len:]
+        ucode_pos = len(nodtb_data) + fdt_len
         fname = tools.GetOutputFilename('test.dtb')
         with open(fname, 'wb') as fd:
-            fd.write(second)
+            fd.write(dtb_with_ucode)
         dtb = fdt.FdtScan(fname)
         ucode = dtb.GetNode('/microcode')
         self.assertTrue(ucode)
         for node in ucode.subnodes:
             self.assertFalse(node.props.get('data'))
 
-        fdt_len = self.GetFdtLen(second)
-        third = second[fdt_len:]
-
         # Check that the microcode appears immediately after the Fdt
         # This matches the concatenation of the data properties in
         # the /microcode/update at xxx nodes in 34_x86_ucode.dts.
         ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
                                  0x78235609)
-        self.assertEqual(ucode_data, third[:len(ucode_data)])
-        ucode_pos = len(nodtb_data) + fdt_len
+        self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
 
         # Check that the microcode pointer was inserted. It should match the
         # expected position and size
Signature · 1 line
2.17.1.1185.g55be947832-goog
#4 lore raw

PATCH 4/29 binman: Correct operation of ObtainContents()

In reply to Simon Glass

This method is supposed to return the contents of an entry. However at present there is no check that it actually does. Also some implementations do not return 'True' to indicate success, as required.

Add a check for things working as expected, and correct the implementations.

This requires some additional test cases to cover things which were missed originally. Add these at the same time.

---

 tools/binman/bsection.py                      |  4 ++
 tools/binman/etype/_testing.py                |  5 ++
 tools/binman/etype/section.py                 |  2 +-
 tools/binman/etype/u_boot_spl_bss_pad.py      |  1 +
 tools/binman/etype/u_boot_ucode.py            |  9 ++-
 tools/binman/ftest.py                         | 57 +++++++++++++++----
 tools/binman/test/57_unknown_contents.dts     | 14 +++++
 .../test/58_x86_ucode_spl_needs_retry.dts     | 36 ++++++++++++
 8 files changed, 114 insertions(+), 14 deletions(-)
 create mode 100644 tools/binman/test/57_unknown_contents.dts
 create mode 100644 tools/binman/test/58_x86_ucode_spl_needs_retry.dts
tools/binman/bsection.py +4 -0
index 3f30f6e4fe7..06a6711350a 100644
@@ -162,6 +162,10 @@ class Section(object):
             todo = next_todo
             if not todo:
                 break
+        if todo:
+            self._Raise('Internal error: Could not complete processing of '
+                        'contents: remaining %s' % todo)
+        return True
 
     def _SetEntryPosSize(self, name, pos, size):
         """Set the position and size of an entry
tools/binman/etype/_testing.py +5 -0
index 0b1eaefc3ce..c075c3ff0d9 100644
@@ -9,6 +9,7 @@ from entry import Entry
 import fdt_util
 import tools
 
+
 class Entry__testing(Entry):
     """A fake entry used for testing
 
@@ -19,8 +20,12 @@ class Entry__testing(Entry):
         Entry.__init__(self, section, etype, node)
         self.return_invalid_entry = fdt_util.GetBool(self._node,
                                                      'return-invalid-entry')
+        self.return_unknown_contents = fdt_util.GetBool(self._node,
+                                                     'return-unknown-contents')
 
     def ObtainContents(self):
+        if self.return_unknown_contents:
+            return False
         self.data = 'a'
         self.contents_size = len(self.data)
         return True
tools/binman/etype/section.py +1 -1
index 139fcad51af..36b31a849f8 100644
@@ -18,7 +18,7 @@ class Entry_section(Entry):
         self._section = bsection.Section(node.name, node)
 
     def ObtainContents(self):
-        self._section.GetEntryContents()
+        return self._section.GetEntryContents()
 
     def GetData(self):
         return self._section.GetData()
tools/binman/etype/u_boot_spl_bss_pad.py +1 -0
index 3d2dea2e0d8..6c397957e30 100644
@@ -24,3 +24,4 @@ class Entry_u_boot_spl_bss_pad(Entry_blob):
             self.Raise('Expected __bss_size symbol in spl/u-boot-spl')
         self.data = chr(0) * bss_size
         self.contents_size = bss_size
+        return True
tools/binman/etype/u_boot_ucode.py +7 -2
index 3a0cff7c3a3..8cae7deed3c 100644
@@ -64,9 +64,14 @@ class Entry_u_boot_ucode(Entry_blob):
             self.data = ''
             return True
 
-        # Get the microcode from the device tree entry
+        # Get the microcode from the device tree entry. If it is not available
+        # yet, return False so we will be called later. If the section simply
+        # doesn't exist, then we may as well return True, since we are going to
+        # get an error anyway.
         fdt_entry = self.section.FindEntryType('u-boot-dtb-with-ucode')
-        if not fdt_entry or not fdt_entry.ucode_data:
+        if not fdt_entry:
+            return True
+        if not fdt_entry.ucode_data:
             return False
 
         if not fdt_entry.collate:
tools/binman/ftest.py +46 -11

104 lines not on this page · raw message

tools/binman/test/57_unknown_contents.dts new file +14 -0
new file mode 100644
index 00000000000..6ea98d7cab6
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		_testing {
+			return-unknown-contents;
+		};
+	};
+};
tools/binman/test/58_x86_ucode_spl_needs_retry.dts new file +36 -0
new file mode 100644
index 00000000000..e2cb80cf6e2
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		sort-by-pos;
+		end-at-4gb;
+		size = <0x200>;
+		u-boot-spl-with-ucode-ptr {
+		};
+
+		/*
+		 * Microcode goes before the DTB which contains it, so binman
+		 * will need to obtain the contents of the next section before
+		 * obtaining the contents of this one.
+		 */
+		u-boot-ucode {
+		};
+
+		u-boot-dtb-with-ucode {
+		};
+	};
+
+	microcode {
+		update at 0 {
+			data = <0x12345678 0x12345679>;
+		};
+		update at 1 {
+			data = <0xabcd0000 0x78235609>;
+		};
+	};
+};
Signature · 1 line
2.17.1.1185.g55be947832-goog
#5 lore raw

PATCH 5/29 binman: Tidy up execution of tests

In reply to Simon Glass

Move all the test execution into the same mechanism so that we can request a particular test (from any suite) by passing it as an argument to 'binman -t'.

---

 tools/binman/binman.py | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
tools/binman/binman.py +3 -5
index f3044ca2124..9bdf2237528 100755
@@ -54,14 +54,12 @@ def RunTests(debug, args):
 
     # Run the entry tests first ,since these need to be the first to import the
     # 'entry' module.
-    suite = unittest.TestLoader().loadTestsFromTestCase(entry_test.TestEntry)
-    suite.run(result)
     test_name = args and args[0] or None
-    for module in (ftest.TestFunctional, fdt_test.TestFdt, elf_test.TestElf,
-                   image_test.TestImage):
+    for module in (entry_test.TestEntry, ftest.TestFunctional, fdt_test.TestFdt,
+                   elf_test.TestElf, image_test.TestImage):
         if test_name:
             try:
-                suite = unittest.TestLoader().loadTestsFromName(args[0], module)
+                suite = unittest.TestLoader().loadTestsFromName(test_name, module)
             except AttributeError:
                 continue
         else:
Signature · 1 line
2.17.1.1185.g55be947832-goog
#6 lore raw

PATCH 6/29 binman: Tidy up setting of entry contents

In reply to Simon Glass

At present the contents of an entry are set in subclasses simply by assigning to the data and content_size properties. Add some methods to do this, so that we have more control. In particular, add a method to set the contents without changing its size, so we can validate that case.

Add a test case for trying to change the size when this is not allowed.

---

 tools/binman/entry.py                       | 28 +++++++++++++++++++++
 tools/binman/etype/_testing.py              |  8 ++++++
 tools/binman/etype/blob.py                  |  3 +--
 tools/binman/etype/u_boot_spl_bss_pad.py    |  3 +--
 tools/binman/etype/u_boot_with_ucode_ptr.py |  4 +--
 tools/binman/ftest.py                       |  8 ++++++
 tools/binman/test/59_change_size.dts        | 14 +++++++++++
 7 files changed, 62 insertions(+), 6 deletions(-)
 create mode 100644 tools/binman/test/59_change_size.dts
tools/binman/entry.py +28 -0
index e4d688c91f9..303c992e375 100644
@@ -55,6 +55,7 @@ class Entry(object):
         self.name = node and (name_prefix + node.name) or 'none'
         self.pos = None
         self.size = None
+        self.data = ''
         self.contents_size = 0
         self.align = None
         self.align_size = None
@@ -138,6 +139,33 @@ class Entry(object):
         if prefix:
             self.name = prefix + self.name
 
+    def SetContents(self, data):
+        """Set the contents of an entry
+
+        This sets both the data and content_size properties
+
+        Args:
+            data: Data to set to the contents (string)
+        """
+        self.data = data
+        self.contents_size = len(self.data)
+
+    def ProcessContentsUpdate(self, data):
+        """Update the contens of an entry, after the size is fixed
+
+        This checks that the new data is the same size as the old.
+
+        Args:
+            data: Data to set to the contents (string)
+
+        Raises:
+            ValueError if the new data size is not the same as the old
+        """
+        if len(data) != self.contents_size:
+            self.Raise('Cannot update entry size from %d to %d' %
+                       (len(data), self.contents_size))
+        self.SetContents(data)
+
     def ObtainContents(self):
         """Figure out the contents of an entry.
 
tools/binman/etype/_testing.py +8 -0
index c075c3ff0d9..04bdc6c532b 100644
@@ -22,6 +22,8 @@ class Entry__testing(Entry):
                                                      'return-invalid-entry')
         self.return_unknown_contents = fdt_util.GetBool(self._node,
                                                      'return-unknown-contents')
+        self.bad_update_contents = fdt_util.GetBool(self._node,
+                                                    'bad-update-contents')
 
     def ObtainContents(self):
         if self.return_unknown_contents:
@@ -34,3 +36,9 @@ class Entry__testing(Entry):
         if self.return_invalid_entry :
             return {'invalid-entry': [1, 2]}
         return {}
+
+    def ProcessContents(self):
+        if self.bad_update_contents:
+            # Request to update the conents with something larger, to cause a
+            # failure.
+            self.ProcessContentsUpdate('aa')
tools/binman/etype/blob.py +1 -2
index 16b1e5f64d9..28e6651a935 100644
@@ -28,8 +28,7 @@ class Entry_blob(Entry):
             # new Entry method which can read in chunks. Then we could copy
             # the data in chunks and avoid reading it all at once. For now
             # this seems like an unnecessary complication.
-            self.data = fd.read()
-            self.contents_size = len(self.data)
+            self.SetContents(fd.read())
         return True
 
     def GetDefaultFilename(self):
tools/binman/etype/u_boot_spl_bss_pad.py +1 -2
index 6c397957e30..65f631d3c5e 100644
@@ -22,6 +22,5 @@ class Entry_u_boot_spl_bss_pad(Entry_blob):
         bss_size = elf.GetSymbolAddress(fname, '__bss_size')
         if not bss_size:
             self.Raise('Expected __bss_size symbol in spl/u-boot-spl')
-        self.data = chr(0) * bss_size
-        self.contents_size = bss_size
+        self.SetContents(chr(0) * bss_size)
         return True
tools/binman/etype/u_boot_with_ucode_ptr.py +2 -2
index 41c2ded2fe8..86945f33184 100644
@@ -81,5 +81,5 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob):
         # Write the microcode position and size into the entry
         pos_and_size = struct.pack('<2L', pos, size)
         self.target_pos -= self.pos
-        self.data = (self.data[:self.target_pos] + pos_and_size +
-                     self.data[self.target_pos + 8:])
+        self.ProcessContentsUpdate(self.data[:self.target_pos] + pos_and_size +
+                                   self.data[self.target_pos + 8:])
tools/binman/ftest.py +8 -0
index ca9d158eef3..af3b4dc3e56 100644
@@ -1006,5 +1006,13 @@ class TestFunctional(unittest.TestCase):
                 "processing of contents: remaining [<_testing.Entry__testing ",
                 str(e.exception))
 
+    def testBadChangeSize(self):
+        """Test that trying to change the size of an entry fails"""
+        with self.assertRaises(ValueError) as e:
+            self._DoReadFile('59_change_size.dts', True)
+        self.assertIn("Node '/binman/_testing': Cannot update entry size from "
+                      '2 to 1', str(e.exception))
+
+
 if __name__ == "__main__":
     unittest.main()
tools/binman/test/59_change_size.dts new file +14 -0
new file mode 100644
index 00000000000..1a69026a64c
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		_testing {
+			bad-update-contents;
+		};
+	};
+};
Signature · 1 line
2.17.1.1185.g55be947832-goog
#7 lore raw

PATCH 7/29 libfdt: Bring in proposed pylibfdt changes

In reply to Simon Glass

This provides various patches sent to the devicetree-compiler mailing list to enhance the Python bindings. A final version of this patch may be created once upstreaming is complete, but if it takes too long, this can act as a placeholder.

New pylibfdt features:
- Support for most remaining, relevant libfdt functions
- Support for sequential-write functions

Changes are applied to existing U-Boot tools as needed.

---

 scripts/dtc/libfdt/libfdt.h           |   3 +
 scripts/dtc/pylibfdt/libfdt.i_shipped | 705 +++++++++++++++++++++++---
 tools/dtoc/dtoc.py                    |  20 +-
 tools/dtoc/fdt.py                     |   3 +-
 tools/dtoc/test_dtoc.py               |   3 +-
 5 files changed, 663 insertions(+), 71 deletions(-)
scripts/dtc/libfdt/libfdt.h +3 -0
index 7f83023ee10..c30aaaeac64 100644
@@ -1310,10 +1310,13 @@ static inline int fdt_property_u64(void *fdt, const char *name, uint64_t val)
 	fdt64_t tmp = cpu_to_fdt64(val);
 	return fdt_property(fdt, name, &tmp, sizeof(tmp));
 }
+
+#ifndef SWIG /* Not available in Python */
 static inline int fdt_property_cell(void *fdt, const char *name, uint32_t val)
 {
 	return fdt_property_u32(fdt, name, val);
 }
+#endif
 
 /**
  * fdt_property_placeholder - add a new property and return a ptr to its value
scripts/dtc/pylibfdt/libfdt.i_shipped +641 -64

812 lines not on this page · raw message

tools/dtoc/dtoc.py +16 -4
index 008c0f4d693..c891b063800 100755
@@ -36,14 +36,26 @@ sys.path.append(os.path.join(our_path, '../patman'))
 
 import dtb_platdata
 
-def run_tests():
-    """Run all the test we have for dtoc"""
+def run_tests(args):
+    """Run all the test we have for dtoc
+
+    Args:
+        args: List of positional args provided to binman. This can hold a test
+            name to execute (as in 'binman -t testSections', for example)
+    """
     import test_dtoc
 
     result = unittest.TestResult()
     sys.argv = [sys.argv[0]]
+    test_name = args and args[0] or None
     for module in (test_dtoc.TestDtoc,):
-        suite = unittest.TestLoader().loadTestsFromTestCase(module)
+        if test_name:
+            try:
+                suite = unittest.TestLoader().loadTestsFromName(test_name, module)
+            except AttributeError:
+                continue
+        else:
+            suite = unittest.TestLoader().loadTestsFromTestCase(module)
         suite.run(result)
 
     print result
@@ -68,7 +80,7 @@ parser.add_option('-t', '--test', action='store_true', dest='test',
 
 # Run our meagre tests
 if options.test:
-    run_tests()
+    run_tests(args)
 
 else:
     dtb_platdata.run_steps(args, options.dtb_file, options.include_disabled,
tools/dtoc/fdt.py +1 -2
index 7fab0cd8e90..d08b0b53e61 100644
@@ -234,7 +234,6 @@ class Node:
         be updated.
         """
         if self._offset != my_offset:
-            #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
             self._offset = my_offset
         offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
         for subnode in self.subnodes:
@@ -359,7 +358,7 @@ class Fdt:
         poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
         while poffset >= 0:
             p = self._fdt_obj.get_property_by_offset(poffset)
-            prop = Prop(node, poffset, p.name, p.value)
+            prop = Prop(node, poffset, p.name, p)
             props_dict[prop.name] = prop
 
             poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
tools/dtoc/test_dtoc.py +2 -1
index 99f4e1a13a4..e475a7eb14e 100644
@@ -4,7 +4,8 @@
 
 """Tests for the dtb_platdata module
 
-This includes unit tests for some functions and functional tests for
+This includes unit tests for some functions and functional tests for the dtoc
+tool.
 """
 
 import collections
Signature · 6 lines
2.17.1.1185.g55be947832-goog

_______________________________________________
U-Boot mailing list
[email protected]
https://lists.denx.de/listinfo/u-boot
#8 lore raw

PATCH 8/29 libfdt: Fix the Python pack() function

In reply to Simon Glass

This currently fails to reduce the device-tree bytearray size. Fix this.

This stands in for a pending upstream change.

---

 scripts/dtc/pylibfdt/libfdt.i_shipped | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
scripts/dtc/pylibfdt/libfdt.i_shipped +5 -1
index 6774b93b2cb..5b38e63b267 100644
@@ -442,7 +442,11 @@ class Fdt:
         Raises:
             FdtException if any error occurs
         """
-        return check_err(fdt_pack(self._fdt), quiet)
+        err = check_err(fdt_pack(self._fdt), quiet)
+        if err:
+            return err
+        del self._fdt[self.totalsize():]
+        return err
 
     def getprop(self, nodeoffset, prop_name, quiet=()):
         """Get a property from a node
Signature · 6 lines
2.17.1.1185.g55be947832-goog

_______________________________________________
U-Boot mailing list
[email protected]
https://lists.denx.de/listinfo/u-boot
#9 lore raw

PATCH 9/29 libfdt: Add get_property() and del_node()

In reply to Simon Glass

Add support for these functions in the Python binding. This patch stands in for a pending upstream change.

---

 scripts/dtc/pylibfdt/libfdt.i_shipped | 32 +++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
scripts/dtc/pylibfdt/libfdt.i_shipped +32 -0
index 5b38e63b267..e180ee93088 100644
@@ -398,6 +398,27 @@ class Fdt:
             return pdata
         return Property(pdata[0], pdata[1])
 
+    def get_property(self, nodeoffset, prop_name, quiet=()):
+        """Obtains a property by name
+
+        Args:
+            nodeoffset: Offset to the node to check
+            prop_name: Name of property to get
+            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(self._fdt, nodeoffset, prop_name), quiet)
+        if isinstance(pdata, (int)):
+            return pdata
+        return Property(pdata[0], pdata[1])
+
     @staticmethod
     def create_empty_tree(size, quiet=()):
         """Create an empty device tree ready for use
@@ -632,6 +653,17 @@ class Fdt:
         """
         return check_err(fdt_node_offset_by_phandle(self._fdt, phandle), quiet)
 
+    def del_node(self, nodeoffset):
+        """Delete a node
+
+        Args:
+            nodeoffset: Node offset containing property to delete
+
+        Raises:
+            FdtError if the node does not exist, or another error occurs
+        """
+        return check_err(fdt_del_node(self._fdt, nodeoffset))
+
 
 class Property(bytearray):
     """Holds a device tree property name and value.
Signature · 6 lines
2.17.1.1185.g55be947832-goog

_______________________________________________
U-Boot mailing list
[email protected]
https://lists.denx.de/listinfo/u-boot
#10 lore raw

PATCH 10/29 binman: Move coverage logic into a new test_util file

In reply to Simon Glass

At present only binman has the logic for determining Python test coverage but this is useful for other tools also. Move it out into a separate file so it can be used by other tools.

---

 tools/binman/binman.py    | 30 +++--------------------
 tools/patman/test_util.py | 51 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 54 insertions(+), 27 deletions(-)
 create mode 100644 tools/patman/test_util.py
tools/binman/binman.py +3 -27
index 9bdf2237528..40438c42780 100755
@@ -26,6 +26,7 @@ sys.path.insert(0, 'scripts/dtc/pylibfdt')
 import cmdline
 import command
 import control
+import test_util
 
 def RunTests(debug, args):
     """Run the functional tests and any embedded doctests
@@ -78,33 +79,8 @@ def RunTests(debug, args):
 
 def RunTestCoverage():
     """Run the tests and check that we get 100% coverage"""
-    # This uses the build output from sandbox_spl to get _libfdt.so
-    cmd = ('PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools python-coverage run '
-            '--include "tools/binman/*.py" --omit "*test*,*binman.py" '
-            'tools/binman/binman.py -t' % options.build_dir)
-    os.system(cmd)
-    stdout = command.Output('python-coverage', 'report')
-    lines = stdout.splitlines()
-
-    test_set= set([os.path.basename(line.split()[0])
-                     for line in lines if '/etype/' in line])
-    glob_list = glob.glob(os.path.join(our_path, 'etype/*.py'))
-    all_set = set([os.path.basename(item) for item in glob_list])
-    missing_list = all_set
-    missing_list.difference_update(test_set)
-    missing_list.remove('_testing.py')
-    coverage = lines[-1].split(' ')[-1]
-    ok = True
-    if missing_list:
-        print 'Missing tests for %s' % (', '.join(missing_list))
-        ok = False
-    if coverage != '100%':
-        print stdout
-        print "Type 'coverage html' to get a report in htmlcov/index.html"
-        print 'Coverage error: %s, but should be 100%%' % coverage
-        ok = False
-    if not ok:
-      raise ValueError('Test coverage failure')
+    test_util.RunTestCoverage('tools/binman/binman.py', None,
+            ['*test*', '*binman.py', 'tools/patman/*', 'tools/dtoc/*'], options.build_dir)
 
 def RunBinman(options, args):
     """Main entry point to binman once arguments are parsed
tools/patman/test_util.py new file +51 -0

51 lines not on this page · raw message

Signature · 1 line
2.17.1.1185.g55be947832-goog
#11 lore raw

PATCH 11/29 dtoc: Add some tests for the fdt module

In reply to Simon Glass

At present this module is tested via the dtoc tests. This is a bit painful since the tests are at a higher level and so failures are more difficult to diagnose.

Add some tests that exercise the fdt module directly.

---

 tools/dtoc/fdt.py      |  12 +-
 tools/dtoc/test_fdt    |   1 +
 tools/dtoc/test_fdt.py | 246 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 257 insertions(+), 2 deletions(-)
 create mode 120000 tools/dtoc/test_fdt
 create mode 100755 tools/dtoc/test_fdt.py
tools/dtoc/fdt.py +10 -2
index d08b0b53e61..5cde8c125ae 100644
@@ -138,6 +138,7 @@ class Prop:
         else:
             return TYPE_INT, val
 
+    @classmethod
     def GetEmpty(self, type):
         """Get an empty / zero value of the given type
 
@@ -335,12 +336,19 @@ class Fdt:
         """
         return self._fdt
 
-    def CheckErr(errnum, msg):
+    def GetFdtObj(self):
+        """Get the contents of the FDT
+
+        Returns:
+            The FDT contents as a libfdt.Fdt object
+        """
+        return self._fdt_obj
+
+    def CheckErr(self, errnum, msg):
         if errnum:
             raise ValueError('Error %d: %s: %s' %
                 (errnum, libfdt.fdt_strerror(errnum), msg))
 
-
     def GetProps(self, node):
         """Get all properties from a node.
 
tools/dtoc/test_fdt new file +1 -0
new file mode 120000
index 00000000000..7c3b23031f0
@@ -0,0 +1 @@
+test_fdt.py
\ No newline at end of file
tools/dtoc/test_fdt.py new file +246 -0

246 lines not on this page · raw message

Signature · 1 line
2.17.1.1185.g55be947832-goog
#12 lore raw

PATCH 12/29 dtoc: Update tests to write failures to /tmp

In reply to Simon Glass

When a test fails due to an output mismatch (e.g. due to a new property being adding to a test file) it is currently hard to update the test to the new output. In particular the tabs in the file are written as \t in the Python tests.

To make this easier, write both the expected and actual results to /tmp to allow use of meld, and copying into the test.

---

 tools/dtoc/test_dtoc.py | 56 ++++++++++++++++++++++++++++++-----------
 1 file changed, 42 insertions(+), 14 deletions(-)
tools/dtoc/test_dtoc.py +42 -14
index e475a7eb14e..ce6d2585a40 100644
@@ -68,6 +68,34 @@ class TestDtoc(unittest.TestCase):
     def tearDownClass(cls):
         tools._RemoveOutputDir()
 
+    def _WritePythonString(self, fname, data):
+        """Write a string with tabs expanded as done in this Python file
+
+        Args:
+            fname: Filename to write to
+            data: Raw string to convert
+        """
+        data = data.replace('\t', '\\t')
+        with open(fname, 'w') as fd:
+            fd.write(data)
+
+    def _CheckStrings(self, expected, actual):
+        """Check that a string matches its expected value
+
+        If the strings do not match, they are written to the /tmp directory in
+        the same Python format as is used here in the test. This allows for
+        easy comparison and update of the tests.
+
+        Args:
+            expected: Expected string
+            actual: Actual string
+        """
+        if expected != actual:
+            self._WritePythonString('/tmp/binman.expected', expected)
+            self._WritePythonString('/tmp/binman.actual', actual)
+            print 'Failures written to /tmp/binman.{expected,actual}'
+        self.assertEquals(expected, actual)
+
     def test_name(self):
         """Test conversion of device tree names to C identifiers"""
         self.assertEqual('serial_at_0x12', conv_name_to_c('serial at 0x12'))
@@ -138,7 +166,7 @@ class TestDtoc(unittest.TestCase):
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_sandbox_i2c_test {
 };
 struct dtd_sandbox_pmic_test {
@@ -162,7 +190,7 @@ struct dtd_sandbox_spl_test_2 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_sandbox_spl_test dtv_spl_test = {
 \t.bytearray\t\t= {0x6, 0x0, 0x0},
 \t.byteval\t\t= 0x5,
@@ -240,7 +268,7 @@ U_BOOT_DEVICE(pmic_at_9) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_source {
 \tstruct phandle_2_arg clocks[4];
 };
@@ -252,7 +280,7 @@ struct dtd_target {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_target dtv_phandle_target = {
 \t.intval\t\t\t= 0x0,
 };
@@ -302,7 +330,7 @@ U_BOOT_DEVICE(phandle_source) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_compat1 {
 \tfdt32_t\t\tintval;
 };
@@ -313,7 +341,7 @@ struct dtd_compat1 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_compat1 dtv_spl_test = {
 \t.intval\t\t\t= 0x1,
 };
@@ -332,7 +360,7 @@ U_BOOT_DEVICE(spl_test) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_test1 {
 \tfdt64_t\t\treg[2];
 };
@@ -347,7 +375,7 @@ struct dtd_test3 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_test1 dtv_test1 = {
 \t.reg\t\t\t= {0x1234, 0x5678},
 };
@@ -384,7 +412,7 @@ U_BOOT_DEVICE(test3) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_test1 {
 \tfdt32_t\t\treg[2];
 };
@@ -396,7 +424,7 @@ struct dtd_test2 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_test1 dtv_test1 = {
 \t.reg\t\t\t= {0x1234, 0x5678},
 };
@@ -424,7 +452,7 @@ U_BOOT_DEVICE(test2) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_test1 {
 \tfdt64_t\t\treg[2];
 };
@@ -439,7 +467,7 @@ struct dtd_test3 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_test1 dtv_test1 = {
 \t.reg\t\t\t= {0x123400000000, 0x5678},
 };
@@ -476,7 +504,7 @@ U_BOOT_DEVICE(test3) = {
         dtb_platdata.run_steps(['struct'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(HEADER + '''
+        self._CheckStrings(HEADER + '''
 struct dtd_test1 {
 \tfdt64_t\t\treg[2];
 };
@@ -491,7 +519,7 @@ struct dtd_test3 {
         dtb_platdata.run_steps(['platdata'], dtb_file, False, output)
         with open(output) as infile:
             data = infile.read()
-        self.assertEqual(C_HEADER + '''
+        self._CheckStrings(C_HEADER + '''
 static struct dtd_test1 dtv_test1 = {
 \t.reg\t\t\t= {0x1234, 0x567800000000},
 };
Signature · 1 line
2.17.1.1185.g55be947832-goog
#13 lore raw

PATCH 13/29 dtoc: Update fdt tests to increase code coverage

In reply to Simon Glass

At present only some of the fdt functionality is tested. Add more tests to cover most things. Also turn on test coverage, which currently sits at 99%.

---

 tools/dtoc/test_fdt.py | 62 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 62 insertions(+)
tools/dtoc/test_fdt.py +62 -0
index ba660ca9b75..6dd24f74e5b 100755
@@ -119,6 +119,8 @@ class TestNode(unittest.TestCase):
         self.node.DeleteProp('intarray')
         offset3 = node2.Offset()
         self.assertTrue(offset3 < offset2)
+        with self.assertRaises(ValueError):
+            self.node.DeleteProp('missing')
 
     def testFindNode(self):
         """Tests that we can find a node using the _FindNode() functoin"""
@@ -126,6 +128,7 @@ class TestNode(unittest.TestCase):
         self.assertEqual('i2c at 0', node.name)
         subnode = node._FindNode('pmic at 9')
         self.assertEqual('pmic@9', subnode.name)
+        self.assertEqual(None, node._FindNode('missing'))
 
 
 class TestProp(unittest.TestCase):
@@ -144,6 +147,53 @@ class TestProp(unittest.TestCase):
         self.node = self.dtb.GetNode('/spl-test')
         self.fdt = self.dtb.GetFdtObj()
 
+    def testPhandle(self):
+        dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
+        node = dtb.GetNode('/phandle-source')
+
+    def _ConvertProp(self, prop_name):
+        """Helper function to look up a property in self.node and return it
+
+        Args:
+            Property name to find
+
+        Return fdt.Prop object for this property
+        """
+        p = self.fdt.get_property(self.node.Offset(), prop_name)
+        return fdt.Prop(self.node, -1, prop_name, p)
+
+    def testMakeProp(self):
+        """Test we can convert all the the types that are supported"""
+        prop = self._ConvertProp('boolval')
+        self.assertEqual(fdt.TYPE_BOOL, prop.type)
+        self.assertEqual(True, prop.value)
+
+        prop = self._ConvertProp('intval')
+        self.assertEqual(fdt.TYPE_INT, prop.type)
+        self.assertEqual(1, fdt32_to_cpu(prop.value))
+
+        prop = self._ConvertProp('intarray')
+        self.assertEqual(fdt.TYPE_INT, prop.type)
+        val = [fdt32_to_cpu(val) for val in prop.value]
+        self.assertEqual([2, 3, 4], val)
+
+        prop = self._ConvertProp('byteval')
+        self.assertEqual(fdt.TYPE_BYTE, prop.type)
+        self.assertEqual(5, ord(prop.value))
+
+        prop = self._ConvertProp('longbytearray')
+        self.assertEqual(fdt.TYPE_BYTE, prop.type)
+        val = [ord(val) for val in prop.value]
+        self.assertEqual([9, 10, 11, 12, 13, 14, 15, 16, 17], val)
+
+        prop = self._ConvertProp('stringval')
+        self.assertEqual(fdt.TYPE_STRING, prop.type)
+        self.assertEqual('message', prop.value)
+
+        prop = self._ConvertProp('stringarray')
+        self.assertEqual(fdt.TYPE_STRING, prop.type)
+        self.assertEqual(['multi-word', 'message'], prop.value)
+
     def testGetEmpty(self):
         """Tests the GetEmpty() function for the various supported types"""
         self.assertEqual(True, fdt.Prop.GetEmpty(fdt.TYPE_BOOL))
@@ -207,6 +257,12 @@ class TestProp(unittest.TestCase):
         self.assertEqual(3, len(prop.value))
 
 
+def RunTestCoverage():
+    """Run the tests and check that we get 100% coverage"""
+    test_util.RunTestCoverage('tools/dtoc/test_fdt.py', '/fdt.py',
+            ['tools/patman/*.py'], options.build_dir)
+
+
 def RunTests(args):
     """Run all the test we have for the fdt model
 
@@ -237,10 +293,16 @@ if __name__ != '__main__':
     sys.exit(1)
 
 parser = OptionParser()
+parser.add_option('-B', '--build-dir', type='string', default='b',
+        help='Directory containing the build output')
 parser.add_option('-t', '--test', action='store_true', dest='test',
                   default=False, help='run tests')
+parser.add_option('-T', '--test-coverage', action='store_true',
+                default=False, help='run tests and check for 100% coverage')
 (options, args) = parser.parse_args()
 
 # Run our meagre tests
 if options.test:
     RunTests(args)
+elif options.test_coverage:
+    RunTestCoverage()
Signature · 1 line
2.17.1.1185.g55be947832-goog
#14 lore raw

PATCH 14/29 dtoc: Make use of the new pylibfdt methods

In reply to Simon Glass

Now that pylibfdt supports a fuller API we don't need to directly call the libfdt stubs. Update the code to use the Fdt methods instead.

Some other cases remain which will be tidied up in a later commit, since they need larger changes.

---

 tools/dtoc/fdt.py | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)
tools/dtoc/fdt.py +14 -12
index 5cde8c125ae..18cde2604ff 100644
@@ -10,6 +10,7 @@ import sys
 
 import fdt_util
 import libfdt
+from libfdt import QUIET_NOTFOUND
 
 # This deals with a device tree, presenting it as an assortment of Node and
 # Prop objects, representing nodes and properties, respectively. This file
@@ -211,22 +212,22 @@ class Node:
         This fills in the props and subnodes properties, recursively
         searching into subnodes so that the entire tree is built.
         """
+        fdt_obj = self._fdt._fdt_obj
         self.props = self._fdt.GetProps(self)
-        phandle = self.props.get('phandle')
+        phandle = fdt_obj.get_phandle(self.Offset())
         if phandle:
-            val = fdt_util.fdt32_to_cpu(phandle.value)
-            self._fdt.phandle_to_node[val] = self
+            self._fdt.phandle_to_node[phandle] = self
 
-        offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
+        offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
         while offset >= 0:
             sep = '' if self.path[-1] == '/' else '/'
-            name = self._fdt._fdt_obj.get_name(offset)
+            name = fdt_obj.get_name(offset)
             path = self.path + sep + name
             node = Node(self._fdt, self, offset, name, path)
             self.subnodes.append(node)
 
             node.Scan()
-            offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
+            offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
 
     def Refresh(self, my_offset):
         """Fix up the _offset for each node, recursively
@@ -324,9 +325,8 @@ class Fdt:
         When nodes and properties shrink or are deleted, wasted space can
         build up in the device tree binary.
         """
-        CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
-        fdt_len = libfdt.fdt_totalsize(self._fdt)
-        del self._fdt[fdt_len:]
+        CheckErr(self._fdt_obj.pack(), 'pack')
+        self.Invalidate()
 
     def GetFdt(self):
         """Get the contents of the FDT
@@ -363,13 +363,15 @@ class Fdt:
             ValueError: if the node does not exist.
         """
         props_dict = {}
-        poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
+        poffset = self._fdt_obj.first_property_offset(node._offset,
+                                                      QUIET_NOTFOUND)
         while poffset >= 0:
             p = self._fdt_obj.get_property_by_offset(poffset)
             prop = Prop(node, poffset, p.name, p)
             props_dict[prop.name] = prop
 
-            poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
+            poffset = self._fdt_obj.next_property_offset(poffset,
+                                                         QUIET_NOTFOUND)
         return props_dict
 
     def Invalidate(self):
@@ -395,7 +397,7 @@ class Fdt:
         Returns:
             Position of @offset within the device tree binary
         """
-        return libfdt.fdt_off_dt_struct(self._fdt) + offset
+        return self._fdt_obj.off_dt_struct() + offset
 
     @classmethod
     def Node(self, fdt, parent, offset, name, path):
Signature · 1 line
2.17.1.1185.g55be947832-goog
#15 lore raw

PATCH 15/29 dtoc: Drop use of a local dtb buffer

In reply to Simon Glass

At present the Fdt class has its own copy of the device tree. This is confusing an unnecessary now that pylibfdt has its own. Drop it and provide access functions to the buffer.

This allows us to move the rest of the implementation to use pylibfdt methods instead of directly calling libfdt stubs.

---

 tools/dtoc/fdt.py      | 16 ++++++++--------
 tools/dtoc/test_fdt.py |  6 +++---
 2 files changed, 11 insertions(+), 11 deletions(-)
tools/dtoc/fdt.py +8 -8
index 18cde2604ff..e24acf12804 100644
@@ -235,12 +235,13 @@ class Node:
         Note: This does not take account of property offsets - these will not
         be updated.
         """
+        fdt_obj = self._fdt._fdt_obj
         if self._offset != my_offset:
             self._offset = my_offset
-        offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
+        offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
         for subnode in self.subnodes:
             subnode.Refresh(offset)
-            offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
+            offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
 
     def DeleteProp(self, prop_name):
         """Delete a property of a node
@@ -252,7 +253,7 @@ class Node:
         Raises:
             ValueError if the property does not exist
         """
-        CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
+        CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
                  "Node '%s': delete property: '%s'" % (self.path, prop_name))
         del self.props[prop_name]
         self._fdt.Invalidate()
@@ -272,8 +273,7 @@ class Fdt:
             self._fname = fdt_util.EnsureCompiled(self._fname)
 
             with open(self._fname) as fd:
-                self._fdt = bytearray(fd.read())
-                self._fdt_obj = libfdt.Fdt(self._fdt)
+                self._fdt_obj = libfdt.Fdt(fd.read())
 
     def Scan(self, root='/'):
         """Scan a device tree, building up a tree of Node objects
@@ -317,7 +317,7 @@ class Fdt:
         If the device tree has changed in memory, write it back to the file.
         """
         with open(self._fname, 'wb') as fd:
-            fd.write(self._fdt)
+            fd.write(self._fdt_obj.as_bytearray())
 
     def Pack(self):
         """Pack the device tree down to its minimum size
@@ -328,13 +328,13 @@ class Fdt:
         CheckErr(self._fdt_obj.pack(), 'pack')
         self.Invalidate()
 
-    def GetFdt(self):
+    def GetContents(self):
         """Get the contents of the FDT
 
         Returns:
             The FDT contents as a string of bytes
         """
-        return self._fdt
+        return self._fdt_obj.as_bytearray()
 
     def GetFdtObj(self):
         """Get the contents of the FDT
tools/dtoc/test_fdt.py +3 -3
index 6dd24f74e5b..ba95a4b77de 100755
@@ -72,7 +72,7 @@ class TestFdt(unittest.TestCase):
 
     def testGetFdt(self):
         """Tetst that we can access the raw device-tree data"""
-        self.assertTrue(isinstance(self.dtb.GetFdt(), bytearray))
+        self.assertTrue(isinstance(self.dtb.GetContents(), bytearray))
 
     def testGetProps(self):
         """Tests obtaining a list of properties"""
@@ -119,7 +119,7 @@ class TestNode(unittest.TestCase):
         self.node.DeleteProp('intarray')
         offset3 = node2.Offset()
         self.assertTrue(offset3 < offset2)
-        with self.assertRaises(ValueError):
+        with self.assertRaises(libfdt.FdtException):
             self.node.DeleteProp('missing')
 
     def testFindNode(self):
@@ -207,7 +207,7 @@ class TestProp(unittest.TestCase):
 
         # Add 12, which is sizeof(struct fdt_property), to get to start of data
         offset = prop.GetOffset() + 12
-        data = self.dtb._fdt[offset:offset + len(prop.value)]
+        data = self.dtb.GetContents()[offset:offset + len(prop.value)]
         bytes = [chr(x) for x in data]
         self.assertEqual(bytes, prop.value)
 
Signature · 1 line
2.17.1.1185.g55be947832-goog
#16 lore raw

PATCH 16/29 dtoc: Keep track of property offsets

In reply to Simon Glass

At present the Fdt class does not keep track of property offsets if they change due to removal of properties. Update the code to handle this, and add a test.

---

 tools/dtoc/fdt.py      | 19 +++++++++++++++++++
 tools/dtoc/test_fdt.py | 39 ++++++++++++++++++++++++++++++++-------
 2 files changed, 51 insertions(+), 7 deletions(-)
tools/dtoc/fdt.py +19 -0
index e24acf12804..2d7b6328f11 100644
@@ -49,6 +49,9 @@ class Prop:
             return
         self.type, self.value = self.BytesToValue(bytes)
 
+    def RefreshOffset(self, poffset):
+        self._offset = poffset
+
     def GetPhandle(self):
         """Get a (single) phandle value from a property
 
@@ -161,6 +164,7 @@ class Prop:
         Returns:
             The offset of the property (struct fdt_property) within the file
         """
+        self._node._fdt.CheckCache()
         return self._node._fdt.GetStructOffset(self._offset)
 
 class Node:
@@ -240,8 +244,22 @@ class Node:
             self._offset = my_offset
         offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
         for subnode in self.subnodes:
+            if subnode.name != fdt_obj.get_name(offset):
+                raise ValueError('Node name mismatch %s != %s' %
+                                 (subnode.name != fdt_obj.get_name(offset)))
             subnode.Refresh(offset)
             offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
+        if offset != -libfdt.FDT_ERR_NOTFOUND:
+            raise ValueError('Internal error, offset == %d' % offset)
+
+        poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
+        while poffset >= 0:
+            p = fdt_obj.get_property_by_offset(poffset)
+            prop = self.props[p.name]
+            prop.RefreshOffset(poffset)
+            poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
+        if poffset != -libfdt.FDT_ERR_NOTFOUND:
+            raise ValueError('Internal error, poffset == %d' % poffset)
 
     def DeleteProp(self, prop_name):
         """Delete a property of a node
@@ -285,6 +303,7 @@ class Fdt:
 
         TODO(sjg at chromium.org): Implement the 'root' parameter
         """
+        self._cached_offsets = True
         self._root = self.Node(self, None, 0, '/', '/')
         self._root.Scan()
 
tools/dtoc/test_fdt.py +32 -7
index ba95a4b77de..cd86144896f 100755
@@ -23,6 +23,30 @@ import libfdt
 import test_util
 import tools
 
+def _GetPropertyValue(dtb, node, prop_name):
+    """Low-level function to get the property value based on its offset
+
+    This looks directly in the device tree at the property's offset to find
+    its value. It is useful as a check that the property is in the correct
+    place.
+
+    Args:
+        node: Node to look in
+        prop_name: Property name to find
+
+    Returns:
+        Tuple:
+            Prop object found
+            Value of property as a string (found using property offset)
+    """
+    prop = node.props[prop_name]
+
+    # Add 12, which is sizeof(struct fdt_property), to get to start of data
+    offset = prop.GetOffset() + 12
+    data = dtb.GetContents()[offset:offset + len(prop.value)]
+    return prop, [chr(x) for x in data]
+
+
 class TestFdt(unittest.TestCase):
     """Tests for the Fdt module
 
@@ -122,6 +146,12 @@ class TestNode(unittest.TestCase):
         with self.assertRaises(libfdt.FdtException):
             self.node.DeleteProp('missing')
 
+    def testDeleteGetOffset(self):
+        """Test that property offset update when properties are deleted"""
+        self.node.DeleteProp('intval')
+        prop, value = _GetPropertyValue(self.dtb, self.node, 'longbytearray')
+        self.assertEqual(prop.value, value)
+
     def testFindNode(self):
         """Tests that we can find a node using the _FindNode() functoin"""
         node = self.dtb.GetRoot()._FindNode('i2c at 0')
@@ -203,13 +233,8 @@ class TestProp(unittest.TestCase):
 
     def testGetOffset(self):
         """Test we can get the offset of a property"""
-        prop = self.node.props['longbytearray']
-
-        # Add 12, which is sizeof(struct fdt_property), to get to start of data
-        offset = prop.GetOffset() + 12
-        data = self.dtb.GetContents()[offset:offset + len(prop.value)]
-        bytes = [chr(x) for x in data]
-        self.assertEqual(bytes, prop.value)
+        prop, value = _GetPropertyValue(self.dtb, self.node, 'longbytearray')
+        self.assertEqual(prop.value, value)
 
     def testWiden(self):
         """Test widening of values"""
Signature · 1 line
2.17.1.1185.g55be947832-goog
#17 lore raw

PATCH 17/29 dtoc: Fix Fdt.GetNode() to handle a missing node

In reply to Simon Glass

At present the algortihm is not correct since it will return the root node if the requested node is not found and there are no slashes in the requested node name. Fix this and add a test.

---

 tools/dtoc/fdt.py      | 5 ++++-
 tools/dtoc/test_fdt.py | 4 ++++
 2 files changed, 8 insertions(+), 1 deletion(-)
tools/dtoc/fdt.py +4 -1
index 2d7b6328f11..fc8aeb81de5 100644
@@ -324,7 +324,10 @@ class Fdt:
             Node object, or None if not found
         """
         node = self._root
-        for part in path.split('/')[1:]:
+        parts = path.split('/')
+        if len(parts) < 2:
+            return None
+        for part in parts[1:]:
             node = node._FindNode(part)
             if not node:
                 return None
tools/dtoc/test_fdt.py +4 -0
index cd86144896f..78afb33b056 100755
@@ -77,6 +77,7 @@ class TestFdt(unittest.TestCase):
         node = self.dtb.GetNode('/i2c at 0/pmic at 9')
         self.assertTrue(isinstance(node, fdt.Node))
         self.assertEqual('pmic at 9', node.name)
+        self.assertEqual(None, self.dtb.GetNode('/i2c at 0/pmic@9/missing'))
 
     def testFlush(self):
         """Check that we can flush the device tree out to its file"""
@@ -177,6 +178,9 @@ class TestProp(unittest.TestCase):
         self.node = self.dtb.GetNode('/spl-test')
         self.fdt = self.dtb.GetFdtObj()
 
+    def testMissingNode(self):
+        self.assertEqual(None, self.dtb.GetNode('missing'))
+
     def testPhandle(self):
         dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
         node = dtb.GetNode('/phandle-source')
Signature · 1 line
2.17.1.1185.g55be947832-goog
#18 lore raw

PATCH 18/29 dtoc: Update fdt tests to increase code coverage

In reply to Simon Glass

At present only some of the fdt functionality is tests. Add more tests to bring code coverage up further.

---

 tools/dtoc/dtoc_test_simple.dts |  1 +
 tools/dtoc/fdt.py               | 16 ++++++---------
 tools/dtoc/test_dtoc.py         |  3 +++
 tools/dtoc/test_fdt.py          | 35 +++++++++++++++++++++++++++++++--
 4 files changed, 43 insertions(+), 12 deletions(-)
tools/dtoc/dtoc_test_simple.dts +1 -0
index 895cc1fea28..a6e2ba8bef7 100644
@@ -21,6 +21,7 @@
 		longbytearray = [09 0a 0b 0c 0d 0e 0f 10 11];
 		stringval = "message";
 		stringarray = "multi-word", "message";
+		stringbad = "message", [01], "junk";
 	};
 
 	spl-test2 {
tools/dtoc/fdt.py +6 -10
index fc8aeb81de5..3595c63a07f 100644
@@ -245,8 +245,8 @@ class Node:
         offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
         for subnode in self.subnodes:
             if subnode.name != fdt_obj.get_name(offset):
-                raise ValueError('Node name mismatch %s != %s' %
-                                 (subnode.name != fdt_obj.get_name(offset)))
+                raise ValueError('Internal error, node name mismatch %s != %s' %
+                                 (subnode.name, fdt_obj.get_name(offset)))
             subnode.Refresh(offset)
             offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
         if offset != -libfdt.FDT_ERR_NOTFOUND:
@@ -255,11 +255,12 @@ class Node:
         poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
         while poffset >= 0:
             p = fdt_obj.get_property_by_offset(poffset)
-            prop = self.props[p.name]
+            prop = self.props.get(p.name)
+            if not prop:
+                raise ValueError("Internal error, property '%s' missing, "
+                                 'offset %d' % (p.name, poffset))
             prop.RefreshOffset(poffset)
             poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
-        if poffset != -libfdt.FDT_ERR_NOTFOUND:
-            raise ValueError('Internal error, poffset == %d' % poffset)
 
     def DeleteProp(self, prop_name):
         """Delete a property of a node
@@ -366,11 +367,6 @@ class Fdt:
         """
         return self._fdt_obj
 
-    def CheckErr(self, errnum, msg):
-        if errnum:
-            raise ValueError('Error %d: %s: %s' %
-                (errnum, libfdt.fdt_strerror(errnum), msg))
-
     def GetProps(self, node):
         """Get all properties from a node.
 
tools/dtoc/test_dtoc.py +3 -0
index ce6d2585a40..95818928b32 100644
@@ -181,6 +181,7 @@ struct dtd_sandbox_spl_test {
 \tfdt32_t\t\tintval;
 \tunsigned char\tlongbytearray[9];
 \tconst char *\tstringarray[3];
+\tunsigned char\tstringbad[14];
 \tconst char *\tstringval;
 };
 struct dtd_sandbox_spl_test_2 {
@@ -195,6 +196,8 @@ static struct dtd_sandbox_spl_test dtv_spl_test = {
 \t.bytearray\t\t= {0x6, 0x0, 0x0},
 \t.byteval\t\t= 0x5,
 \t.intval\t\t\t= 0x1,
+\t.stringbad\t\t= {0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x0,
+\t\t0x1, 0x6a, 0x75, 0x6e, 0x6b, 0x0},
 \t.longbytearray\t\t= {0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10,
 \t\t0x11},
 \t.stringval\t\t= "message",
tools/dtoc/test_fdt.py +33 -2
index 78afb33b056..d6ea1951001 100755
@@ -105,13 +105,13 @@ class TestFdt(unittest.TestCase):
         props = self.dtb.GetProps(node)
         self.assertEqual(['boolval', 'bytearray', 'byteval', 'compatible',
                           'intarray', 'intval', 'longbytearray',
-                          'stringarray', 'stringval', 'u-boot,dm-pre-reloc'],
+                          'stringarray', 'stringbad', 'stringval', 'u-boot,dm-pre-reloc'],
                          sorted(props.keys()))
 
     def testCheckError(self):
         """Tests the ChecKError() function"""
         with self.assertRaises(ValueError) as e:
-            self.dtb.CheckErr(-libfdt.NOTFOUND, 'hello')
+            fdt.CheckErr(-libfdt.NOTFOUND, 'hello')
         self.assertIn('FDT_ERR_NOTFOUND: hello', str(e.exception))
 
 
@@ -161,6 +161,32 @@ class TestNode(unittest.TestCase):
         self.assertEqual('pmic at 9', subnode.name)
         self.assertEqual(None, node._FindNode('missing'))
 
+    def testRefreshMissingNode(self):
+        """Test refreshing offsets when an extra node is present in dtb"""
+        # Delete it from our tables, not the device tree
+        del self.dtb._root.subnodes[-1]
+        with self.assertRaises(ValueError) as e:
+            self.dtb.Refresh()
+        self.assertIn('Internal error, offset', str(e.exception))
+
+    def testRefreshExtraNode(self):
+        """Test refreshing offsets when an expected node is missing"""
+        # Delete it from the device tre, not our tables
+        self.dtb.GetFdtObj().del_node(self.node.Offset())
+        with self.assertRaises(ValueError) as e:
+            self.dtb.Refresh()
+        self.assertIn('Internal error, node name mismatch '
+                      'spl-test != spl-test2', str(e.exception))
+
+    def testRefreshMissingProp(self):
+        """Test refreshing offsets when an extra property is present in dtb"""
+        # Delete it from our tables, not the device tree
+        del self.node.props['stringbad']
+        with self.assertRaises(ValueError) as e:
+            self.dtb.Refresh()
+        self.assertIn("Internal error, property 'stringbad' missing, offset ",
+                      str(e.exception))
+
 
 class TestProp(unittest.TestCase):
     """Test operation of the Prop class"""
@@ -228,6 +254,11 @@ class TestProp(unittest.TestCase):
         self.assertEqual(fdt.TYPE_STRING, prop.type)
         self.assertEqual(['multi-word', 'message'], prop.value)
 
+        prop = self._ConvertProp('stringbad')
+        self.assertEqual(fdt.TYPE_BYTE, prop.type)
+        val = [ch for ch in 'message\x00\x01junk\0']
+        self.assertEqual(val, prop.value)
+
     def testGetEmpty(self):
         """Tests the GetEmpty() function for the various supported types"""
         self.assertEqual(True, fdt.Prop.GetEmpty(fdt.TYPE_BOOL))
Signature · 1 line
2.17.1.1185.g55be947832-goog
#19 lore raw

PATCH 19/29 dtoc: Fix properties with a single zero-arg phandle

In reply to Simon Glass

At present a property with a single phandle looks like an integer value to dtoc. Correct this by adjusting it in the phandle-processing code.

Add a test for this, so that code coverage increases to 100%.

---

 tools/dtoc/dtb_platdata.py       | 12 ++++++++----
 tools/dtoc/dtoc_test_phandle.dts |  6 ++++++
 tools/dtoc/test_dtoc.py          | 10 ++++++++++
 tools/dtoc/test_fdt.py           |  4 +++-
 4 files changed, 27 insertions(+), 5 deletions(-)
tools/dtoc/dtb_platdata.py +8 -4
index 2f7302e5295..b1323aef198 100644
@@ -211,15 +211,21 @@ class DtbPlatdata(object):
             Number of argument cells is this is a phandle, else None
         """
         if prop.name in ['clocks']:
+            if not isinstance(prop.value, list):
+                prop.value = [prop.value]
             val = prop.value
-            if not isinstance(val, list):
-                val = [val]
             i = 0
 
             max_args = 0
             args = []
             while i < len(val):
                 phandle = fdt_util.fdt32_to_cpu(val[i])
+                # If we get to the end of the list, stop. This can happen
+                # since some nodes have more phandles in the list than others,
+                # but we allocate enough space for the largest list. So those
+                # nodes with shorter lists end up with zeroes@the end.
+                if not phandle:
+                    break
                 target = self._fdt.phandle_to_node.get(phandle)
                 if not target:
                     raise ValueError("Cannot parse '%s' in node '%s'" %
@@ -400,8 +406,6 @@ class DtbPlatdata(object):
                     continue
                 info = self.get_phandle_argc(prop, node.name)
                 if info:
-                    if not isinstance(prop.value, list):
-                        prop.value = [prop.value]
                     # Process the list as pairs of (phandle, id)
                     pos = 0
                     for args in info.args:
tools/dtoc/dtoc_test_phandle.dts +6 -0
index 91dfec5c63f..a71acffc698 100644
@@ -33,4 +33,10 @@
 		compatible = "source";
 		clocks = <&phandle &phandle_1 11 &phandle_2 12 13 &phandle>;
 	};
+
+	phandle-source2 {
+		u-boot,dm-pre-reloc;
+		compatible = "source";
+		clocks = <&phandle>;
+	};
 };
tools/dtoc/test_dtoc.py +10 -0
index 95818928b32..41a4c53bb9d 100644
@@ -324,6 +324,16 @@ U_BOOT_DEVICE(phandle_source) = {
 \t.platdata_size\t= sizeof(dtv_phandle_source),
 };
 
+static struct dtd_source dtv_phandle_source2 = {
+\t.clocks\t\t\t= {
+\t\t\t{&dtv_phandle_target, {}},},
+};
+U_BOOT_DEVICE(phandle_source2) = {
+\t.name\t\t= "source",
+\t.platdata\t= &dtv_phandle_source2,
+\t.platdata_size\t= sizeof(dtv_phandle_source2),
+};
+
 ''', data)
 
     def test_aliases(self):
tools/dtoc/test_fdt.py +3 -1
index d6ea1951001..97b8cbb794e 100755
@@ -209,7 +209,9 @@ class TestProp(unittest.TestCase):
 
     def testPhandle(self):
         dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
-        node = dtb.GetNode('/phandle-source')
+        node = dtb.GetNode('/phandle-source2')
+        prop = node.props['clocks']
+        self.assertTrue(prop.GetPhandle() > 0)
 
     def _ConvertProp(self, prop_name):
         """Helper function to look up a property in self.node and return it
Signature · 1 line
2.17.1.1185.g55be947832-goog
#20 lore raw

PATCH 20/29 dtoc: Fix some minor errors

In reply to Simon Glass

Fix some comments and a printf string which is incorrect.

---

 tools/dtoc/dtb_platdata.py | 3 ++-
 tools/dtoc/dtoc.py         | 4 ++--
 tools/dtoc/fdt.py          | 2 +-
 3 files changed, 5 insertions(+), 4 deletions(-)
tools/dtoc/dtb_platdata.py +2 -1
index b1323aef198..6cb12594466 100644
@@ -316,7 +316,8 @@ class DtbPlatdata(object):
             total = na + ns
 
             if reg.type != fdt.TYPE_INT:
-                raise ValueError("Node '%s' reg property is not an int")
+                raise ValueError("Node '%s' reg property is not an int" %
+                                 node.name)
             if len(reg.value) % total:
                 raise ValueError("Node '%s' reg property has %d cells "
                         'which is not a multiple of na + ns = %d + %d)' %
tools/dtoc/dtoc.py +2 -2
index c891b063800..2e6a4db8bc1 100755
@@ -40,8 +40,8 @@ def run_tests(args):
     """Run all the test we have for dtoc
 
     Args:
-        args: List of positional args provided to binman. This can hold a test
-            name to execute (as in 'binman -t testSections', for example)
+        args: List of positional args provided to dtoc. This can hold a test
+            name to execute (as in 'dtoc -t test_empty_file', for example)
     """
     import test_dtoc
 
tools/dtoc/fdt.py +1 -1
index 3595c63a07f..f11fb75b1a4 100644
@@ -435,7 +435,7 @@ class Fdt:
         return node
 
 def FdtScan(fname):
-    """Returns a new Fdt object from the implementation we are using"""
+    """Returns a new Fdt object"""
     dtb = Fdt(fname)
     dtb.Scan()
     return dtb
Signature · 1 line
2.17.1.1185.g55be947832-goog
#21 lore raw

PATCH 21/29 dtoc: Add a test for code coverage

In reply to Simon Glass

Add a -T option to run a code-coverage test on dtoc. At present this is about 96%. Future work will increase it to 100%.

---

 tools/dtoc/dtoc.py | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
tools/dtoc/dtoc.py +15 -0
index 2e6a4db8bc1..1fbc2db6e46 100755
@@ -35,6 +35,7 @@ our_path = os.path.dirname(os.path.realpath(__file__))
 sys.path.append(os.path.join(our_path, '../patman'))
 
 import dtb_platdata
+import test_util
 
 def run_tests(args):
     """Run all the test we have for dtoc
@@ -64,10 +65,19 @@ def run_tests(args):
     for _, err in result.failures:
         print err
 
+def RunTestCoverage():
+    """Run the tests and check that we get 100% coverage"""
+    sys.argv = [sys.argv[0]]
+    test_util.RunTestCoverage('tools/dtoc/dtoc.py', '/dtb_platdata.py',
+            ['tools/patman/*.py'], options.build_dir)
+
+
 if __name__ != '__main__':
     sys.exit(1)
 
 parser = OptionParser()
+parser.add_option('-B', '--build-dir', type='string', default='b',
+        help='Directory containing the build output')
 parser.add_option('-d', '--dtb-file', action='store',
                   help='Specify the .dtb input file')
 parser.add_option('--include-disabled', action='store_true',
@@ -76,12 +86,17 @@ parser.add_option('-o', '--output', action='store', default='-',
                   help='Select output filename')
 parser.add_option('-t', '--test', action='store_true', dest='test',
                   default=False, help='run tests')
+parser.add_option('-T', '--test-coverage', action='store_true',
+                default=False, help='run tests and check for 100% coverage')
 (options, args) = parser.parse_args()
 
 # Run our meagre tests
 if options.test:
     run_tests(args)
 
+elif options.test_coverage:
+    RunTestCoverage()
+
 else:
     dtb_platdata.run_steps(args, options.dtb_file, options.include_disabled,
                            options.output)
Signature · 1 line
2.17.1.1185.g55be947832-goog
#22 lore raw

PATCH 22/29 dtoc: Increase code coverage to 100%

In reply to Simon Glass

Add more tests to increase dtoc code coverage to 100%.

Correct a whitespace error in some test .dts files at the same time.

---

 tools/dtoc/dtoc_test_add_prop.dts        |  24 ++++
 tools/dtoc/dtoc_test_addr32_64.dts       |   2 +-
 tools/dtoc/dtoc_test_addr64_32.dts       |   2 +-
 tools/dtoc/dtoc_test_bad_reg.dts         |  17 +++
 tools/dtoc/dtoc_test_bad_reg2.dts        |  17 +++
 tools/dtoc/dtoc_test_phandle_bad.dts     |  16 +++
 tools/dtoc/dtoc_test_phandle_bad2.dts    |  22 ++++
 tools/dtoc/dtoc_test_phandle_reorder.dts |  23 ++++
 tools/dtoc/dtoc_test_phandle_single.dts  |  23 ++++
 tools/dtoc/test_dtoc.py                  | 142 +++++++++++++++++++++++
 10 files changed, 286 insertions(+), 2 deletions(-)
 create mode 100644 tools/dtoc/dtoc_test_add_prop.dts
 create mode 100644 tools/dtoc/dtoc_test_bad_reg.dts
 create mode 100644 tools/dtoc/dtoc_test_bad_reg2.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_bad.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_bad2.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_reorder.dts
 create mode 100644 tools/dtoc/dtoc_test_phandle_single.dts
tools/dtoc/dtoc_test_add_prop.dts new file +24 -0
new file mode 100644
index 00000000000..fa296e55527
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+	spl-test {
+		u-boot,dm-pre-reloc;
+		compatible = "sandbox,spl-test";
+		intval = <1>;
+	};
+
+	spl-test2 {
+		u-boot,dm-pre-reloc;
+		compatible = "sandbox,spl-test";
+		intarray = <5>;
+	};
+};
tools/dtoc/dtoc_test_addr32_64.dts +1 -1
index 7891ee59fa2..7599d5b0a59 100644
@@ -5,7 +5,7 @@
  * Copyright 2017 Google, Inc
  */
 
- /dts-v1/;
+/dts-v1/;
 
 / {
 	#address-cells = <1>;
tools/dtoc/dtoc_test_addr64_32.dts +1 -1
index 759a7e8e265..85e4f5fdaeb 100644
@@ -5,7 +5,7 @@
  * Copyright 2017 Google, Inc
  */
 
- /dts-v1/;
+/dts-v1/;
 
 / {
 	#address-cells = <2>;
tools/dtoc/dtoc_test_bad_reg.dts new file +17 -0
new file mode 100644
index 00000000000..1312acb619b
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+	spl-test {
+	compatible = "test";
+		reg = "fre";
+	};
+};
tools/dtoc/dtoc_test_bad_reg2.dts new file +17 -0
new file mode 100644
index 00000000000..3e9efa43af1
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+	spl-test {
+	compatible = "test";
+		reg = <1 2 3>;
+	};
+};
tools/dtoc/dtoc_test_phandle_bad.dts new file +16 -0
new file mode 100644
index 00000000000..a3ddc595851
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	phandle-source {
+		u-boot,dm-pre-reloc;
+		compatible = "source";
+		clocks = <20>;    /* Invalid phandle */
+	};
+};
tools/dtoc/dtoc_test_phandle_bad2.dts new file +22 -0
new file mode 100644
index 00000000000..fe25f565fbb
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	phandle: phandle-target {
+		u-boot,dm-pre-reloc;
+		compatible = "target";
+		intval = <0>;
+	};
+
+	phandle-source2 {
+		u-boot,dm-pre-reloc;
+		compatible = "source";
+		clocks = <&phandle>;
+	};
+};
tools/dtoc/dtoc_test_phandle_reorder.dts new file +23 -0
new file mode 100644
index 00000000000..aa71d56f27c
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+
+	phandle-source2 {
+		u-boot,dm-pre-reloc;
+		compatible = "source";
+		clocks = <&phandle>;
+	};
+
+	phandle: phandle-target {
+		u-boot,dm-pre-reloc;
+		compatible = "target";
+		#clock-cells = <0>;
+	};
+};
tools/dtoc/dtoc_test_phandle_single.dts new file +23 -0
new file mode 100644
index 00000000000..aacd0b15fa1
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Test device tree file for dtoc
+ *
+ * Copyright 2018 Google, Inc
+ */
+
+/dts-v1/;
+
+/ {
+	phandle: phandle-target {
+		u-boot,dm-pre-reloc;
+		compatible = "target";
+		intval = <0>;
+		#clock-cells = <0>;
+	};
+
+	phandle-source2 {
+		u-boot,dm-pre-reloc;
+		compatible = "source";
+		clocks = <&phandle>;
+	};
+};
tools/dtoc/test_dtoc.py +142 -0

157 lines not on this page · raw message

Signature · 1 line
2.17.1.1185.g55be947832-goog
#23 lore raw

PATCH 23/29 binman: Move capture_sys_output() to test_util

In reply to Simon Glass

This function is useful in various tests. Move it into the common test utility module.

---

 tools/binman/elf_test.py   | 22 ++--------------------
 tools/binman/image_test.py |  2 +-
 tools/patman/test_util.py  | 22 ++++++++++++++++++++++
 3 files changed, 25 insertions(+), 21 deletions(-)
tools/binman/elf_test.py +2 -20
index fb6e451cf0e..9c8f1feca85 100644
@@ -4,33 +4,15 @@
 #
 # Test for the elf module
 
-from contextlib import contextmanager
 import os
 import sys
 import unittest
 
-try:
-  from StringIO import StringIO
-except ImportError:
-  from io import StringIO
-
 import elf
+import test_util
 
 binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
 
-# Use this to suppress stdout/stderr output:
-# with capture_sys_output() as (stdout, stderr)
-#   ...do something...
- at contextmanager
-def capture_sys_output():
-  capture_out, capture_err = StringIO(), StringIO()
-  old_out, old_err = sys.stdout, sys.stderr
-  try:
-    sys.stdout, sys.stderr = capture_out, capture_err
-    yield capture_out, capture_err
-  finally:
-    sys.stdout, sys.stderr = old_out, old_err
-
 
 class FakeEntry:
     def __init__(self, contents_size):
@@ -110,7 +92,7 @@ class TestElf(unittest.TestCase):
         entry = FakeEntry(20)
         section = FakeSection()
         elf_fname = os.path.join(binman_dir, 'test', 'u_boot_binman_syms')
-        with capture_sys_output() as (stdout, stderr):
+        with test_util.capture_sys_output() as (stdout, stderr):
             syms = elf.LookupAndWriteSymbols(elf_fname, entry, section)
         elf.debug = False
         self.assertTrue(len(stdout.getvalue()) > 0)
tools/binman/image_test.py +1 -1
index 45dd2378c8a..3775e1afb07 100644
@@ -7,7 +7,7 @@
 import unittest
 
 from image import Image
-from elf_test import capture_sys_output
+from test_util import capture_sys_output
 
 class TestImage(unittest.TestCase):
     def testInvalidFormat(self):
tools/patman/test_util.py +22 -0
index a240f383777..d159509e812 100644
@@ -3,12 +3,19 @@
 # Copyright (c) 2016 Google, Inc
 #
 
+from contextlib import contextmanager
 import glob
 import os
 import sys
 
 import command
 
+try:
+  from StringIO import StringIO
+except ImportError:
+  from io import StringIO
+
+
 def RunTestCoverage(prog, filter_fname, exclude_list, build_dir):
     """Run tests and check that we get 100% coverage
 
@@ -49,3 +56,18 @@ def RunTestCoverage(prog, filter_fname, exclude_list, build_dir):
         ok = False
     if not ok:
       raise ValueError('Test coverage failure')
+
+
+# Use this to suppress stdout/stderr output:
+# with capture_sys_output() as (stdout, stderr)
+#   ...do something...
+ at contextmanager
+def capture_sys_output():
+    capture_out, capture_err = StringIO(), StringIO()
+    old_out, old_err = sys.stdout, sys.stderr
+    try:
+        sys.stdout, sys.stderr = capture_out, capture_err
+        yield capture_out, capture_err
+    finally:
+        sys.stdout, sys.stderr = old_out, old_err
+
Signature · 1 line
2.17.1.1185.g55be947832-goog
#24 lore raw

PATCH 24/29 dtoc: Avoid unwanted output during tests

In reply to Simon Glass

At present some warnings are printed to indicate failures which are a known part of running the tests. Suppress these.

---

 tools/dtoc/fdt_util.py  |  4 ++--
 tools/dtoc/test_dtoc.py | 13 +++++++++----
 2 files changed, 11 insertions(+), 6 deletions(-)
tools/dtoc/fdt_util.py +2 -2
index 2d09649f720..e7f5a809093 100644
@@ -44,7 +44,7 @@ def fdt_cells_to_cpu(val, cells):
         out = out << 32 | fdt32_to_cpu(val[1])
     return out
 
-def EnsureCompiled(fname):
+def EnsureCompiled(fname, capture_stderr=False):
     """Compile an fdt .dts source file into a .dtb binary blob if needed.
 
     Args:
@@ -79,7 +79,7 @@ def EnsureCompiled(fname):
     args.extend(search_list)
     args.append(dts_input)
     dtc = os.environ.get('DTC') or 'dtc'
-    command.Run(dtc, *args)
+    command.Run(dtc, *args, capture_stderr=capture_stderr)
     return dtb_output
 
 def GetInt(node, propname, default=None):
tools/dtoc/test_dtoc.py +9 -4
index 95ecabc3a17..d48cf392d81 100644
@@ -47,16 +47,19 @@ C_HEADER = '''/*
 '''
 
 
-def get_dtb_file(dts_fname):
+
+def get_dtb_file(dts_fname, capture_stderr=False):
     """Compile a .dts file to a .dtb
 
     Args:
         dts_fname: Filename of .dts file in the current directory
+        capture_stderr: True to capture and discard stderr output
 
     Returns:
         Filename of compiled file in output directory
     """
-    return fdt_util.EnsureCompiled(os.path.join(our_path, dts_fname))
+    return fdt_util.EnsureCompiled(os.path.join(our_path, dts_fname),
+                                   capture_stderr=capture_stderr)
 
 
 class TestDtoc(unittest.TestCase):
@@ -627,7 +630,8 @@ U_BOOT_DEVICE(test3) = {
 
     def test_bad_reg(self):
         """Test that a reg property with an invalid type generates an error"""
-        dtb_file = get_dtb_file('dtoc_test_bad_reg.dts')
+        # Capture stderr since dtc will emit warnings for this file
+        dtb_file = get_dtb_file('dtoc_test_bad_reg.dts', capture_stderr=True)
         output = tools.GetOutputFilename('output')
         with self.assertRaises(ValueError) as e:
             dtb_platdata.run_steps(['struct'], dtb_file, False, output)
@@ -636,7 +640,8 @@ U_BOOT_DEVICE(test3) = {
 
     def test_bad_reg2(self):
         """Test that a reg property with an invalid cell count is detected"""
-        dtb_file = get_dtb_file('dtoc_test_bad_reg2.dts')
+        # Capture stderr since dtc will emit warnings for this file
+        dtb_file = get_dtb_file('dtoc_test_bad_reg2.dts', capture_stderr=True)
         output = tools.GetOutputFilename('output')
         with self.assertRaises(ValueError) as e:
             dtb_platdata.run_steps(['struct'], dtb_file, False, output)
Signature · 1 line
2.17.1.1185.g55be947832-goog
#25 lore raw

PATCH 25/29 dtoc: Add functions to add integer properties

In reply to Simon Glass

Add a few simple functions to add a placeholder integer property, and set its value.

---

 tools/dtoc/fdt.py      | 27 +++++++++++++++++++++++++++
 tools/dtoc/test_fdt.py | 20 ++++++++++++++++++++
 2 files changed, 47 insertions(+)
tools/dtoc/fdt.py +27 -0
index f11fb75b1a4..7282b7e021c 100644
@@ -277,6 +277,33 @@ class Node:
         del self.props[prop_name]
         self._fdt.Invalidate()
 
+    def AddZeroProp(self, prop_name):
+        """Add a new property to the device tree with an integer value of 0.
+
+        Args:
+            prop_name: Name of property
+        """
+        fdt_obj = self._fdt._fdt_obj
+        if fdt_obj.setprop_u32(self.Offset(), prop_name, 0,
+                               (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
+            fdt_obj.open_into(fdt_obj.totalsize() + 1024)
+            fdt_obj.setprop_u32(self.Offset(), prop_name, 0)
+        self.props[prop_name] = Prop(self, -1, prop_name, '\0' * 4)
+        self._fdt.Invalidate()
+
+    def SetInt(self, prop_name, val):
+        """Update an integer property int the device tree.
+
+        This is not allowed to change the size of the FDT.
+
+        Args:
+            prop_name: Name of property
+            val: Value to set
+        """
+        fdt_obj = self._fdt._fdt_obj
+        fdt_obj.setprop_u32(self.Offset(), prop_name, val)
+
+
 class Fdt:
     """Provides simple access to a flat device tree blob using libfdts.
 
tools/dtoc/test_fdt.py +20 -0
index 97b8cbb794e..0bc4bd64646 100755
@@ -318,6 +318,26 @@ class TestProp(unittest.TestCase):
         self.assertTrue(isinstance(prop.value, list))
         self.assertEqual(3, len(prop.value))
 
+    def testAdd(self):
+        """Test adding properties"""
+        self.fdt.pack()
+        # This function should automatically expand the device tree
+        self.node.AddZeroProp('one')
+        self.node.AddZeroProp('two')
+        self.node.AddZeroProp('three')
+
+        # Updating existing properties should be OK, since the device-tree size
+        # does not change
+        self.fdt.pack()
+        self.node.SetInt('one', 1)
+        self.node.SetInt('two', 2)
+        self.node.SetInt('three', 3)
+
+        # This should fail since it would need to increase the device-tree size
+        with self.assertRaises(libfdt.FdtException) as e:
+            self.node.SetInt('four', 4)
+        self.assertIn('FDT_ERR_NOSPACE', str(e.exception))
+
 
 def RunTestCoverage():
     """Run the tests and check that we get 100% coverage"""
Signature · 1 line
2.17.1.1185.g55be947832-goog
#26 lore raw

PATCH 26/29 binman: Complete documentation of stages

In reply to Simon Glass

At present one of the stages is badly numbered and not described. Fix this.

---

 tools/binman/README | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
tools/binman/README +4 -2
index f74e39242f6..3cfcf84d92c 100644
@@ -495,9 +495,11 @@ contents of an entry in some way. For example, it would be possible to create
 an entry containing a hash of the contents of some other entries. At this
 stage the position and size of entries should not be adjusted.
 
-6. WriteEntryInfo()
+7. WriteSymbols() - write the value of symbols into the U-Boot SPL binary.
+See 'Access to binman entry positions at run time' below for a description of
+what happens in this stage.
 
-7. BuildImage() - builds the image and writes it to a file. This is the final
+8. BuildImage() - builds the image and writes it to a file. This is the final
 step.
 
 
Signature · 1 line
2.17.1.1185.g55be947832-goog
#27 lore raw

PATCH 27/29 binman: Add a ProcessFdt() method

In reply to Simon Glass

Some entry types modify the device tree, e.g. to remove microcode or add a property. So far this just modifies their local copy and does not affect a 'shared' device tree.

Rather than doing this modification in the ObtainContents() method, and a new ProcessFdt() method which is specifically designed to modify this shared device tree.

Move the existing device-tree code over to use this method, reducing ObtainContents() to the goal of just obtaining the contents without any processing, even for device tree.

---

 tools/binman/README                         | 23 +++++----
 tools/binman/bsection.py                    | 15 ++++++
 tools/binman/control.py                     | 52 ++++++++++++++++++++-
 tools/binman/entry.py                       |  3 ++
 tools/binman/etype/section.py               |  3 ++
 tools/binman/etype/u_boot_dtb_with_ucode.py | 47 ++++++++++---------
 tools/binman/etype/u_boot_ucode.py          |  2 +-
 tools/binman/etype/u_boot_with_ucode_ptr.py |  7 ++-
 tools/binman/image.py                       |  3 ++
 9 files changed, 118 insertions(+), 37 deletions(-)
tools/binman/README +15 -8
index 3cfcf84d92c..008d5750528 100644
@@ -462,7 +462,14 @@ Order of image creation
 
 Image creation proceeds in the following order, for each entry in the image.
 
-1. GetEntryContents() - the contents of each entry are obtained, normally by
+1. ProcessFdt() - process the device tree information as required by the
+particular entry. This may involve adding or deleting properties. If the
+processing is complete, this method should return True. If the processing
+cannot complete because it needs the ProcessFdt() method of another entry to
+run first, this method should return False, in which case it will be called
+again later.
+
+2. GetEntryContents() - the contents of each entry are obtained, normally by
 reading from a file. This calls the Entry.ObtainContents() to read the
 contents. The default version of Entry.ObtainContents() calls
 Entry.GetDefaultFilename() and then reads that file. So a common mechanism
@@ -471,35 +478,35 @@ functions must return True when they have read the contents. Binman will
 retry calling the functions a few times if False is returned, allowing
 dependencies between the contents of different entries.
 
-2. GetEntryPositions() - calls Entry.GetPositions() for each entry. This can
+3. GetEntryPositions() - calls Entry.GetPositions() for each entry. This can
 return a dict containing entries that need updating. The key should be the
 entry name and the value is a tuple (pos, size). This allows an entry to
 provide the position and size for other entries. The default implementation
 of GetEntryPositions() returns {}.
 
-3. PackEntries() - calls Entry.Pack() which figures out the position and
+4. PackEntries() - calls Entry.Pack() which figures out the position and
 size of an entry. The 'current' image position is passed in, and the function
 returns the position immediately after the entry being packed. The default
 implementation of Pack() is usually sufficient.
 
-4. CheckSize() - checks that the contents of all the entries fits within
+5. CheckSize() - checks that the contents of all the entries fits within
 the image size. If the image does not have a defined size, the size is set
 large enough to hold all the entries.
 
-5. CheckEntries() - checks that the entries do not overlap, nor extend
+6. CheckEntries() - checks that the entries do not overlap, nor extend
 outside the image.
 
-6. ProcessEntryContents() - this calls Entry.ProcessContents() on each entry.
+7. ProcessEntryContents() - this calls Entry.ProcessContents() on each entry.
 The default implementatoin does nothing. This can be overriden to adjust the
 contents of an entry in some way. For example, it would be possible to create
 an entry containing a hash of the contents of some other entries. At this
 stage the position and size of entries should not be adjusted.
 
-7. WriteSymbols() - write the value of symbols into the U-Boot SPL binary.
+8. WriteSymbols() - write the value of symbols into the U-Boot SPL binary.
 See 'Access to binman entry positions at run time' below for a description of
 what happens in this stage.
 
-8. BuildImage() - builds the image and writes it to a file. This is the final
+9. BuildImage() - builds the image and writes it to a file. This is the final
 step.
 
 
tools/binman/bsection.py +15 -0
index 06a6711350a..3ed361d69a2 100644
@@ -90,6 +90,21 @@ class Section(object):
             entry.SetPrefix(self._name_prefix)
             self._entries[node.name] = entry
 
+    def ProcessFdt(self, fdt):
+        todo = self._entries.values()
+        for passnum in range(3):
+            next_todo = []
+            for entry in todo:
+                if not entry.ProcessFdt(fdt):
+                    next_todo.append(entry)
+            todo = next_todo
+            if not todo:
+                break
+        if todo:
+            self._Raise('Internal error: Could not complete processing of Fdt: '
+                        'remaining %s' % todo)
+        return True
+
     def CheckSize(self):
         """Check that the section contents does not exceed its size, etc."""
         contents_size = 0
tools/binman/control.py +51 -1

75 lines not on this page · raw message

tools/binman/entry.py +3 -0
index 303c992e375..62e65c91266 100644
@@ -130,6 +130,9 @@ class Entry(object):
         self.align_end = fdt_util.GetInt(self._node, 'align-end')
         self.pos_unset = fdt_util.GetBool(self._node, 'pos-unset')
 
+    def ProcessFdt(self, fdt):
+        return True
+
     def SetPrefix(self, prefix):
         """Set the name prefix for a node
 
tools/binman/etype/section.py +3 -0
index 36b31a849f8..9b38738d38d 100644
@@ -17,6 +17,9 @@ class Entry_section(Entry):
         Entry.__init__(self, image, etype, node)
         self._section = bsection.Section(node.name, node)
 
+    def ProcessFdt(self, fdt):
+        return self._section.ProcessFdt(fdt)
+
     def ObtainContents(self):
         return self._section.GetEntryContents()
 
tools/binman/etype/u_boot_dtb_with_ucode.py +24 -23

79 lines not on this page · raw message

tools/binman/etype/u_boot_ucode.py +1 -1
index 8cae7deed3c..ea0c85cc5c7 100644
@@ -71,7 +71,7 @@ class Entry_u_boot_ucode(Entry_blob):
         fdt_entry = self.section.FindEntryType('u-boot-dtb-with-ucode')
         if not fdt_entry:
             return True
-        if not fdt_entry.ucode_data:
+        if not fdt_entry.ready:
             return False
 
         if not fdt_entry.collate:
tools/binman/etype/u_boot_with_ucode_ptr.py +3 -4
index 86945f33184..8b1e41152e3 100644
@@ -28,7 +28,7 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob):
     def GetDefaultFilename(self):
         return 'u-boot-nodtb.bin'
 
-    def ObtainContents(self):
+    def ProcessFdt(self, fdt):
         # Figure out where to put the microcode pointer
         fname = tools.GetInputFilename(self.elf_fname)
         sym = elf.GetSymbolAddress(fname, '_dt_ucode_base_size')
@@ -36,8 +36,7 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob):
            self.target_pos = sym
         elif not fdt_util.GetBool(self._node, 'optional-ucode'):
             self.Raise('Cannot locate _dt_ucode_base_size symbol in u-boot')
-
-        return Entry_blob.ObtainContents(self)
+        return True
 
     def ProcessContents(self):
         # If the image does not need microcode, there is nothing to do
@@ -73,7 +72,7 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob):
             pos, size = ucode_entry.pos, ucode_entry.size
         else:
             dtb_entry = self.section.FindEntryType('u-boot-dtb-with-ucode')
-            if not dtb_entry:
+            if not dtb_entry or not dtb_entry.ready:
                 self.Raise('Cannot find microcode region u-boot-dtb-with-ucode')
             pos = dtb_entry.pos + dtb_entry.ucode_offset
             size = dtb_entry.ucode_size
tools/binman/image.py +3 -0
index 835b66c99f5..9732493709c 100644
@@ -54,6 +54,9 @@ class Image:
             self._filename = filename
         self._section = bsection.Section('main-section', self._node)
 
+    def ProcessFdt(self, fdt):
+        return self._section.ProcessFdt(fdt)
+
     def GetEntryContents(self):
         """Call ObtainContents() for the section
         """
Signature · 1 line
2.17.1.1185.g55be947832-goog
#28 lore raw

PATCH 28/29 binman: Add a SetCalculatedProperties() method

In reply to Simon Glass

Once binman has packed the image, the position and size of each entry is known. It is then possible for binman to update the device tree with these positions. Since placeholder values have been added, this does not affect the size of the device tree and therefore the packing does not need to be performed again.

Add a new SetCalculatedProperties method to handle this.

---

 tools/binman/README           | 29 ++++++++++++++++++++---------
 tools/binman/bsection.py      |  8 ++++++++
 tools/binman/cmdline.py       |  2 ++
 tools/binman/control.py       |  4 ++++
 tools/binman/entry.py         | 11 +++++++++++
 tools/binman/etype/section.py |  8 ++++++++
 tools/binman/image.py         | 14 ++++++++++++++
 7 files changed, 67 insertions(+), 9 deletions(-)
tools/binman/README +20 -9
index 008d5750528..8b598a75c80 100644
@@ -462,14 +462,22 @@ Order of image creation
 
 Image creation proceeds in the following order, for each entry in the image.
 
-1. ProcessFdt() - process the device tree information as required by the
+1. AddMissingProperties() - binman can add calculated values to the device
+tree as part of its processing, for example the position and size of each
+entry. This method adds any properties associated with this, expanding the
+device tree as needed. These properties can have placeholder values which are
+set later by SetCalculatedProperties(). By that stage the size of sections
+cannot be changed (since it would cause the images to need to be repacked),
+but the correct values can be inserted.
+
+2. ProcessFdt() - process the device tree information as required by the
 particular entry. This may involve adding or deleting properties. If the
 processing is complete, this method should return True. If the processing
 cannot complete because it needs the ProcessFdt() method of another entry to
 run first, this method should return False, in which case it will be called
 again later.
 
-2. GetEntryContents() - the contents of each entry are obtained, normally by
+3. GetEntryContents() - the contents of each entry are obtained, normally by
 reading from a file. This calls the Entry.ObtainContents() to read the
 contents. The default version of Entry.ObtainContents() calls
 Entry.GetDefaultFilename() and then reads that file. So a common mechanism
@@ -478,35 +486,38 @@ functions must return True when they have read the contents. Binman will
 retry calling the functions a few times if False is returned, allowing
 dependencies between the contents of different entries.
 
-3. GetEntryPositions() - calls Entry.GetPositions() for each entry. This can
+4. GetEntryPositions() - calls Entry.GetPositions() for each entry. This can
 return a dict containing entries that need updating. The key should be the
 entry name and the value is a tuple (pos, size). This allows an entry to
 provide the position and size for other entries. The default implementation
 of GetEntryPositions() returns {}.
 
-4. PackEntries() - calls Entry.Pack() which figures out the position and
+5. PackEntries() - calls Entry.Pack() which figures out the position and
 size of an entry. The 'current' image position is passed in, and the function
 returns the position immediately after the entry being packed. The default
 implementation of Pack() is usually sufficient.
 
-5. CheckSize() - checks that the contents of all the entries fits within
+6. CheckSize() - checks that the contents of all the entries fits within
 the image size. If the image does not have a defined size, the size is set
 large enough to hold all the entries.
 
-6. CheckEntries() - checks that the entries do not overlap, nor extend
+7. CheckEntries() - checks that the entries do not overlap, nor extend
 outside the image.
 
-7. ProcessEntryContents() - this calls Entry.ProcessContents() on each entry.
+8. SetCalculatedProperties() - update any calculated properties in the device
+tree. This sets the correct 'pos' and 'size' vaues, for example.
+
+9. ProcessEntryContents() - this calls Entry.ProcessContents() on each entry.
 The default implementatoin does nothing. This can be overriden to adjust the
 contents of an entry in some way. For example, it would be possible to create
 an entry containing a hash of the contents of some other entries. At this
 stage the position and size of entries should not be adjusted.
 
-8. WriteSymbols() - write the value of symbols into the U-Boot SPL binary.
+10. WriteSymbols() - write the value of symbols into the U-Boot SPL binary.
 See 'Access to binman entry positions at run time' below for a description of
 what happens in this stage.
 
-9. BuildImage() - builds the image and writes it to a file. This is the final
+11. BuildImage() - builds the image and writes it to a file. This is the final
 step.
 
 
tools/binman/bsection.py +8 -0
index 3ed361d69a2..de439ef625f 100644
@@ -90,6 +90,14 @@ class Section(object):
             entry.SetPrefix(self._name_prefix)
             self._entries[node.name] = entry
 
+    def AddMissingProperties(self):
+        for entry in self._entries.values():
+            entry.AddMissingProperties()
+
+    def SetCalculatedProperties(self):
+        for entry in self._entries.values():
+            entry.SetCalculatedProperties()
+
     def ProcessFdt(self, fdt):
         todo = self._entries.values()
         for passnum in range(3):
tools/binman/cmdline.py +2 -0
index bf63919eb79..ae2d1670f9a 100644
@@ -42,6 +42,8 @@ def ParseArgs(argv):
                     default=False, help='run tests')
     parser.add_option('-T', '--test-coverage', action='store_true',
                     default=False, help='run tests and check for 100% coverage')
+    parser.add_option('-u', '--update-fdt', action='store_true',
+        default=False, help='Update the binman node with position/size info')
     parser.add_option('-v', '--verbosity', default=1,
         type='int', help='Control verbosity: 0=silent, 1=progress, 3=full, '
         '4=debug')
tools/binman/control.py +4 -0
index 5325a6a0066..eafabf05c7c 100644
@@ -144,6 +144,8 @@ def Binman(options, args):
             # without changing the device-tree size, thus ensuring that our
             # entry positions remain the same.
             for image in images.values():
+                if options.update_fdt:
+                    image.AddMissingProperties()
                 image.ProcessFdt(dtb)
 
             dtb.Pack()
@@ -159,6 +161,8 @@ def Binman(options, args):
                 image.PackEntries()
                 image.CheckSize()
                 image.CheckEntries()
+                if options.update_fdt:
+                    image.SetCalculatedProperties()
                 image.ProcessEntryContents()
                 image.WriteSymbols()
                 image.BuildImage()
tools/binman/entry.py +11 -0
index 62e65c91266..6a173e663d0 100644
@@ -130,6 +130,17 @@ class Entry(object):
         self.align_end = fdt_util.GetInt(self._node, 'align-end')
         self.pos_unset = fdt_util.GetBool(self._node, 'pos-unset')
 
+    def AddMissingProperties(self):
+        """Add new properties to the device tree as needed for this entry"""
+        for prop in ['pos', 'size']:
+            if not prop in self._node.props:
+                self._node.AddZeroProp(prop)
+
+    def SetCalculatedProperties(self):
+        """Set the value of device-tree properties calculated by binman"""
+        self._node.SetInt('pos', self.pos)
+        self._node.SetInt('size', self.size)
+
     def ProcessFdt(self, fdt):
         return True
 
tools/binman/etype/section.py +8 -0
index 9b38738d38d..787257d3ec1 100644
@@ -20,6 +20,10 @@ class Entry_section(Entry):
     def ProcessFdt(self, fdt):
         return self._section.ProcessFdt(fdt)
 
+    def AddMissingProperties(self):
+        Entry.AddMissingProperties(self)
+        self._section.AddMissingProperties()
+
     def ObtainContents(self):
         return self._section.GetEntryContents()
 
@@ -45,6 +49,10 @@ class Entry_section(Entry):
         """Write symbol values into binary files for access at run time"""
         self._section.WriteSymbols()
 
+    def SetCalculatedProperties(self):
+        Entry.SetCalculatedProperties(self)
+        self._section.SetCalculatedProperties()
+
     def ProcessContents(self):
         self._section.ProcessEntryContents()
         super(Entry_section, self).ProcessContents()
tools/binman/image.py +14 -0
index 9732493709c..94028f19a51 100644
@@ -54,6 +54,17 @@ class Image:
             self._filename = filename
         self._section = bsection.Section('main-section', self._node)
 
+    def AddMissingProperties(self):
+        """Add properties that are not present in the device tree
+
+        When binman has completed packing the entries the position and size of
+        each entry are known. But before this the device tree may not specify
+        these. Add any missing properties, with a dummy value, so that the
+        size of the entry is correct. That way we can insert the correct values
+        later.
+        """
+        self._section.AddMissingProperties()
+
     def ProcessFdt(self, fdt):
         return self._section.ProcessFdt(fdt)
 
@@ -82,6 +93,9 @@ class Image:
         """Check that entries do not overlap or extend outside the image"""
         self._section.CheckEntries()
 
+    def SetCalculatedProperties(self):
+        self._section.SetCalculatedProperties()
+
     def ProcessEntryContents(self):
         """Call the ProcessContents() method for each entry
 
Signature · 1 line
2.17.1.1185.g55be947832-goog
#29 lore raw

PATCH 29/29 binman: Support updating the device tree with calc'd info

In reply to Simon Glass

It is useful to write the position and size of each entry back to the device tree so that U-Boot can access this at runtime. Add a feature to support this, along with associated tests.

---

 tools/binman/README                 |  6 +--
 tools/binman/control.py             |  2 +
 tools/binman/ftest.py               | 69 ++++++++++++++++++++++++-----
 tools/binman/test/60_fdt_update.dts | 28 ++++++++++++
 4 files changed, 91 insertions(+), 14 deletions(-)
 create mode 100644 tools/binman/test/60_fdt_update.dts
tools/binman/README +2 -4
index 8b598a75c80..207928aa955 100644
@@ -669,13 +669,11 @@ To do
 -----
 
 Some ideas:
-- Fill out the device tree to include the final position and size of each
-  entry (since the input file may not always specify these). See also
-  'Access to binman entry positions at run time' above
 - Use of-platdata to make the information available to code that is unable
   to use device tree (such as a very small SPL image)
 - Allow easy building of images by specifying just the board name
-- Produce a full Python binding for libfdt (for upstream)
+- Produce a full Python binding for libfdt (for upstream). This is nearing
+    completion but some work remains
 - Add an option to decode an image into the constituent binaries
 - Support building an image for a board (-b) more completely, with a
   configurable build directory
tools/binman/control.py +2 -0
index eafabf05c7c..a40b300fdac 100644
@@ -168,6 +168,8 @@ def Binman(options, args):
                 image.BuildImage()
                 if options.map:
                     image.WriteMap()
+            with open(fname, 'wb') as outfd:
+                outfd.write(dtb.GetContents())
         finally:
             tools.FinaliseOutputDir()
     finally:
tools/binman/ftest.py +59 -10

145 lines not on this page · raw message

tools/binman/test/60_fdt_update.dts new file +28 -0
new file mode 100644
index 00000000000..28e483fd7b5
@@ -0,0 +1,28 @@
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pad-byte = <0x26>;
+		size = <0x28>;
+		section at 0 {
+			read-only;
+			name-prefix = "ro-";
+			size = <0x10>;
+			pad-byte = <0x21>;
+
+			u-boot {
+			};
+		};
+		section at 1 {
+			name-prefix = "rw-";
+			size = <0x10>;
+			pad-byte = <0x61>;
+
+			u-boot {
+			};
+		};
+	};
+};
Signature · 1 line
2.17.1.1185.g55be947832-goog