source: mainline/tools/xstruct.py@ 25ebfbd

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 25ebfbd was cc1a727, checked in by Martin Sucha <sucha14@…>, 14 years ago

Add support for ext2 to be used as RAM disk format

  • Property mode set to 100644
File size: 4.4 KB
RevLine 
[8c25a4a]1#
2# Copyright (c) 2008 Martin Decky
[cc1a727]3# Copyright (c) 2011 Martin Sucha
[8c25a4a]4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9#
10# - Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12# - Redistributions in binary form must reproduce the above copyright
13# notice, this list of conditions and the following disclaimer in the
14# documentation and/or other materials provided with the distribution.
15# - The name of the author may not be used to endorse or promote products
16# derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29"""
[0516fd7]30Convert descriptive structure definitions to structure object
[8c25a4a]31"""
32
33import struct
[cc1a727]34import types
35
36ranges = {
37 'B': ((int, long), 0x00, 0xff),
38 'H': ((int, long), 0x0000, 0xffff),
39 'L': ((int, long), 0x00000000, 0xffffffff),
40 'Q': ((int, long), 0x0000000000000000, 0xffffffffffffffff),
41 'b': ((int, long), -0x80, 0x7f),
42 'h': ((int, long), -0x8000, 0x7fff),
43 'l': ((int, long), -0x80000000, 0x7fffffff) ,
44 'q': ((int, long), -0x8000000000000000, 0x7fffffffffffffff),
45}
46
47def check_range(varname, fmt, value):
48 if value == None:
49 raise ValueError('Variable "%s" not set' % varname)
50 if not fmt in ranges:
51 return
52 vartype, varmin, varmax = ranges[fmt]
53 if not isinstance(value, vartype):
54 raise ValueError('Variable "%s" is %s but should be %s' %
55 (varname, str(type(value)), str(vartype)))
56 if value < varmin or value > varmax:
57 raise ValueError('Variable "%s" value %s out of range %s..%s' %
58 (varname, repr(value), repr(varmin), repr(varmax)))
[8c25a4a]59
[0516fd7]60class Struct:
61 def size(self):
62 return struct.calcsize(self._format_)
63
64 def pack(self):
[5749372]65 args = []
[cc1a727]66 for variable, fmt, length in self._args_:
67 value = self.__dict__[variable]
68 if isinstance(value, list):
69 if length != None and length != len(value):
70 raise ValueError('Variable "%s" length %u does not match %u' %
71 (variable, len(value), length))
72 for index, item in enumerate(value):
73 check_range(variable + '[' + repr(index) + ']', fmt, item)
[5749372]74 args.append(item)
75 else:
[cc1a727]76 check_range(variable, fmt, value)
77 args.append(value)
[5749372]78 return struct.pack(self._format_, *args)
[cc1a727]79
80 def unpack(self, data):
81 values = struct.unpack(self._format_, data)
82 i = 0
83 for variable, fmt, length in self._args_:
84 self.__dict__[variable] = values[i]
85 i += 1
[0516fd7]86
87def create(definition):
88 "Create structure object"
[8c25a4a]89
90 tokens = definition.split(None)
91
92 # Initial byte order tag
[0516fd7]93 format = {
[8c25a4a]94 "little:": lambda: "<",
95 "big:": lambda: ">",
96 "network:": lambda: "!"
97 }[tokens[0]]()
[0516fd7]98 inst = Struct()
[5749372]99 args = []
[b3105ff6]100
[8c25a4a]101 # Member tags
[b3105ff6]102 comment = False
[8f2a852]103 variable = None
[8c25a4a]104 for token in tokens[1:]:
[b3105ff6]105 if (comment):
106 if (token == "*/"):
107 comment = False
108 continue
109
110 if (token == "/*"):
111 comment = True
[8f2a852]112 continue
113
114 if (variable != None):
115 subtokens = token.split("[")
116
[cc1a727]117 length = None
[8f2a852]118 if (len(subtokens) > 1):
[cc1a727]119 length = int(subtokens[1].split("]")[0])
120 format += "%d" % length
[8f2a852]121
122 format += variable
123
124 inst.__dict__[subtokens[0]] = None
[cc1a727]125 args.append((subtokens[0], variable, length))
[8f2a852]126
127 variable = None
128 continue
129
130 if (token[0:8] == "padding["):
[0516fd7]131 size = token[8:].split("]")[0]
132 format += "%dx" % int(size)
[8f2a852]133 continue
134
135 variable = {
136 "char": lambda: "s",
137 "uint8_t": lambda: "B",
138 "uint16_t": lambda: "H",
139 "uint32_t": lambda: "L",
140 "uint64_t": lambda: "Q",
141
142 "int8_t": lambda: "b",
143 "int16_t": lambda: "h",
144 "int32_t": lambda: "l",
145 "int64_t": lambda: "q"
146 }[token]()
[8c25a4a]147
[0516fd7]148 inst.__dict__['_format_'] = format
[5749372]149 inst.__dict__['_args_'] = args
[0516fd7]150 return inst
Note: See TracBrowser for help on using the repository browser.