1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  * libfdt - Flat Device Tree manipulation
4  *	Testcase for misbehaviour on a truncated string
5  * Copyright (C) 2018 David Gibson, IBM Corporation.
6  */
7 
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdint.h>
12 
13 #include <libfdt.h>
14 
15 #include "tests.h"
16 #include "testdata.h"
17 
main(int argc,char * argv[])18 int main(int argc, char *argv[])
19 {
20 	void *fdt = &truncated_string;
21 	const struct fdt_property *good, *bad;
22 	int off, len;
23 	const char *name;
24 
25 	test_init(argc, argv);
26 
27 	vg_prepare_blob(fdt, fdt_totalsize(fdt));
28 
29 	off = fdt_first_property_offset(fdt, 0);
30 	good = fdt_get_property_by_offset(fdt, off, NULL);
31 
32 	off = fdt_next_property_offset(fdt, off);
33 	bad = fdt_get_property_by_offset(fdt, off, NULL);
34 
35 	if (fdt32_to_cpu(good->len) != 0)
36 		FAIL("Unexpected length for good property");
37 	name = fdt_get_string(fdt, fdt32_to_cpu(good->nameoff), &len);
38 	if (!name)
39 		FAIL("fdt_get_string() failed on good property: %s",
40 		     fdt_strerror(len));
41 	if (len != 4)
42 		FAIL("fdt_get_string() returned length %d (not 4) on good property",
43 		     len);
44 	if (!streq(name, "good"))
45 		FAIL("fdt_get_string() returned \"%s\" (not \"good\") on good property",
46 		     name);
47 
48 	if (fdt32_to_cpu(bad->len) != 0)
49 		FAIL("Unexpected length for bad property\n");
50 	name = fdt_get_string(fdt, fdt32_to_cpu(bad->nameoff), &len);
51 	if (name)
52 		FAIL("fdt_get_string() succeeded incorrectly on bad property");
53 	else if (len != -FDT_ERR_TRUNCATED)
54 		FAIL("fdt_get_string() gave unexpected error on bad property: %s",
55 		     fdt_strerror(len));
56 
57 	/* Make sure the 'good' property breaks correctly if we
58 	 * truncate the strings section */
59 	fdt_set_size_dt_strings(fdt, fdt32_to_cpu(good->nameoff) + 4);
60 	name = fdt_get_string(fdt, fdt32_to_cpu(good->nameoff), &len);
61 	if (name)
62 		FAIL("fdt_get_string() succeeded incorrectly on mangled property");
63 	else if (len != -FDT_ERR_TRUNCATED)
64 		FAIL("fdt_get_string() gave unexpected error on mangled property: %s",
65 		     fdt_strerror(len));
66 
67 	PASS();
68 }
69