aboutsummaryrefslogtreecommitdiffstats
path: root/dtc/tests/path-references.c
blob: 0746b3f7e324d8232f089fe2b0cb2ce3594ffb5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * libfdt - Flat Device Tree manipulation
 *	Testcase for string references in dtc
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#include <libfdt.h>

#include "tests.h"
#include "testdata.h"

static void check_ref(const void *fdt, int node, const char *checkpath)
{
	const char *p;
	int len;

	p = fdt_getprop(fdt, node, "ref", &len);
	if (!p)
		FAIL("fdt_getprop(%d, \"ref\"): %s", node, fdt_strerror(len));
	if (!streq(p, checkpath))
		FAIL("'ref' in node at %d has value \"%s\" instead of \"%s\"",
		     node, p, checkpath);

	p = fdt_getprop(fdt, node, "lref", &len);
	if (!p)
		FAIL("fdt_getprop(%d, \"lref\"): %s", node, fdt_strerror(len));
	if (!streq(p, checkpath))
		FAIL("'lref' in node at %d has value \"%s\" instead of \"%s\"",
		     node, p, checkpath);
}

int main(int argc, char *argv[])
{
	void *fdt;
	const char *p;
	int len, multilen;
	int n1, n2;

	test_init(argc, argv);
	fdt = load_blob_arg(argc, argv);

	n1 = fdt_path_offset(fdt, "/node1");
	if (n1 < 0)
		FAIL("fdt_path_offset(/node1): %s", fdt_strerror(n1));
	n2 = fdt_path_offset(fdt, "/node2");
	if (n2 < 0)
		FAIL("fdt_path_offset(/node2): %s", fdt_strerror(n2));

	check_ref(fdt, n1, "/node2");
	check_ref(fdt, n2, "/node1");

	/* Check multiple reference */
	multilen = strlen("/node1") + strlen("/node2") + 2;
	p = fdt_getprop(fdt, 0, "multiref", &len);
	if (!p)
		FAIL("fdt_getprop(0, \"multiref\"): %s", fdt_strerror(len));
	if (len != multilen)
		FAIL("multiref has wrong length, %d instead of %d",
		     len, multilen);
	if ((!streq(p, "/node1") || !streq(p + strlen("/node1") + 1, "/node2")))
		FAIL("multiref has wrong value");

	PASS();
}
9;uR', 'U', 'UR', 'L', 'LR')) # Token types. UNKNOWN = 'UNKNOWN' SYNTAX = 'SYNTAX' CONSTANT = 'CONSTANT' NAME = 'NAME' PREPROCESSOR = 'PREPROCESSOR' # Where the token originated from. This can be used for backtracking. # It is always set to WHENCE_STREAM in this code. WHENCE_STREAM, WHENCE_QUEUE = range(2) class Token(object): """Data container to represent a C++ token. Tokens can be identifiers, syntax char(s), constants, or pre-processor directives. start contains the index of the first char of the token in the source end contains the index of the last char of the token in the source """ def __init__(self, token_type, name, start, end): self.token_type = token_type self.name = name self.start = start self.end = end self.whence = WHENCE_STREAM def __str__(self): if not utils.DEBUG: return 'Token(%r)' % self.name return 'Token(%r, %s, %s)' % (self.name, self.start, self.end) __repr__ = __str__ def _GetString(source, start, i): i = source.find('"', i+1) while source[i-1] == '\\': # Count the trailing backslashes. backslash_count = 1 j = i - 2 while source[j] == '\\': backslash_count += 1 j -= 1 # When trailing backslashes are even, they escape each other. if (backslash_count % 2) == 0: break i = source.find('"', i+1) return i + 1 def _GetChar(source, start, i): # NOTE(nnorwitz): may not be quite correct, should be good enough. i = source.find("'", i+1) while source[i-1] == '\\': # Need to special case '\\'. if (i - 2) > start and source[i-2] == '\\': break i = source.find("'", i+1) # Try to handle unterminated single quotes (in a #if 0 block). if i < 0: i = start return i + 1 def GetTokens(source): """Returns a sequence of Tokens. Args: source: string of C++ source code. Yields: Token that represents the next token in the source. """ # Cache various valid character sets for speed. valid_identifier_chars = VALID_IDENTIFIER_CHARS hex_digits = HEX_DIGITS int_or_float_digits = INT_OR_FLOAT_DIGITS int_or_float_digits2 = int_or_float_digits | set('.') # Only ignore errors while in a #if 0 block. ignore_errors = False count_ifs = 0 i = 0 end = len(source) while i < end: # Skip whitespace. while i < end and source[i].isspace(): i += 1 if i >= end: return token_type = UNKNOWN start = i c = source[i] if c.isalpha() or c == '_': # Find a string token. token_type = NAME while source[i] in valid_identifier_chars: i += 1 # String and character constants can look like a name if # they are something like L"". if (source[i] == "'" and (i - start) == 1 and source[start:i] in 'uUL'): # u, U, and L are valid C++0x character preffixes. token_type = CONSTANT i = _GetChar(source, start, i) elif source[i] == "'" and source[start:i] in _STR_PREFIXES: token_type = CONSTANT i = _GetString(source, start, i) elif c == '/' and source[i+1] == '/': # Find // comments. i = source.find('\n', i) if i == -1: # Handle EOF. i = end continue elif c == '/' and source[i+1] == '*': # Find /* comments. */ i = source.find('*/', i) + 2 continue elif c in ':+-<>&|*=': # : or :: (plus other chars). token_type = SYNTAX i += 1 new_ch = source[i] if new_ch == c and c != '>': # Treat ">>" as two tokens. i += 1 elif c == '-' and new_ch == '>': i += 1 elif new_ch == '=': i += 1 elif c in '()[]{}~!?^%;/.,': # Handle single char tokens. token_type = SYNTAX i += 1 if c == '.' and source[i].isdigit(): token_type = CONSTANT i += 1 while source[i] in int_or_float_digits: i += 1 # Handle float suffixes. for suffix in ('l', 'f'): if suffix == source[i:i+1].lower(): i += 1 break elif c.isdigit(): # Find integer. token_type = CONSTANT if c == '0' and source[i+1] in 'xX': # Handle hex digits. i += 2 while source[i] in hex_digits: i += 1 else: while source[i] in int_or_float_digits2: i += 1 # Handle integer (and float) suffixes. for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'): size = len(suffix) if suffix == source[i:i+size].lower(): i += size break elif c == '"': # Find string. token_type = CONSTANT i = _GetString(source, start, i) elif c == "'": # Find char. token_type = CONSTANT i = _GetChar(source, start, i) elif c == '#': # Find pre-processor command. token_type = PREPROCESSOR got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace() if got_if: count_ifs += 1 elif source[i:i+6] == '#endif': count_ifs -= 1 if count_ifs == 0: ignore_errors = False # TODO(nnorwitz): handle preprocessor statements (\ continuations). while 1: i1 = source.find('\n', i) i2 = source.find('//', i) i3 = source.find('/*', i) i4 = source.find('"', i) # NOTE(nnorwitz): doesn't handle comments in #define macros. # Get the first important symbol (newline, comment, EOF/end). i = min([x for x in (i1, i2, i3, i4, end) if x != -1]) # Handle #include "dir//foo.h" properly. if source[i] == '"': i = source.find('"', i+1) + 1 assert i > 0 continue # Keep going if end of the line and the line ends with \. if not (i == i1 and source[i-1] == '\\'): if got_if: condition = source[start+4:i].lstrip() if (condition.startswith('0') or condition.startswith('(0)')): ignore_errors = True break i += 1 elif c == '\\': # Handle \ in code. # This is different from the pre-processor \ handling. i += 1 continue elif ignore_errors: # The tokenizer seems to be in pretty good shape. This # raise is conditionally disabled so that bogus code # in an #if 0 block can be handled. Since we will ignore # it anyways, this is probably fine. So disable the # exception and return the bogus char. i += 1 else: sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' % ('?', i, c, source[i-10:i+10])) raise RuntimeError('unexpected token') if i <= 0: print('Invalid index, exiting now.') return yield Token(token_type, source[start:i], start, i) if __name__ == '__main__': def main(argv): """Driver mostly for testing purposes.""" for filename in argv[1:]: source = utils.ReadFile(filename) if source is None: continue for token in GetTokens(source): print('%-12s: %s' % (token.token_type, token.name)) # print('\r%6.2f%%' % (100.0 * index / token.end),) sys.stdout.write('\n') main(sys.argv)