]> git.ozlabs.org Git - bitfield/blob - bitfield
Add support for aliased definitions.
[bitfield] / bitfield
1 #!/usr/bin/python2.4
2 #
3 # Utility to decode register values
4 # Copyright (c) 2006 Jeremy Kerr <jk@ozlabs.org>
5 # Released under the GNU General Public License version 2 or later
6 #
7 # Documentation and updates at: http://ozlabs.org/~jk/code/bitfield
8
9 import os
10 import sys
11 import pprint
12 from pyparsing import Literal, Word, ZeroOrMore, Group, Dict, Optional, \
13         printables, ParseException, restOfLine
14 from getopt import getopt, GetoptError
15
16 # List of paths to look for configuration files. If a directory is specified,
17 # it will be (recursively) scanned for .conf files.
18 configs = ["/etc/bitfield.d", "/etc/bitfield",
19                 os.path.join(os.getenv("HOME"), ".bitfield.d"),
20                 os.path.join(os.getenv("HOME"), ".bitfield.conf")]
21
22 class bitfield:
23         def __init__(self, bits, name):
24                 self.bits = bits
25                 self.name = name
26                 self.values = {}
27
28         def width(self):
29                 return len(self.bits)
30
31         def add_value(self, value, description):
32                 self.values[int(value)] = description
33
34         def mask(self, reg_width, value):
35                 ret = 0
36                 out_len = len(self.bits)
37                 for out_bit in range(0, out_len):
38                         in_bit = self.bits[out_bit]
39                         # shift this bit down to the LSB (and mask the rest)
40                         i = (value >> (reg_width - in_bit - 1)) & 1
41                         # shift back to the output position in the field
42                         i <<= out_len - out_bit - 1
43                         ret |= i
44                 return ret
45
46         def value(self, value):
47                 if value in self.values:
48                         return self.values[value]
49                 return None
50
51         @staticmethod
52         def parse_bitfield(line):
53                 a = line.split(None, 1)
54                 if len(a) != 2:
55                         return None
56                 (range_str, name) = a
57
58                 bits = []
59                 for s in range_str.split(','):
60                         if ':' in s:
61                                 (start, end) = s.split(':')
62                                 bits.extend(range(int(start), int(end) + 1, 1))
63                         else:
64                                 bits.append(int(s))
65  
66                 return bitfield(bits, name)
67
68         @staticmethod
69         def parse_value(line):
70                 a = line.split(None, 1)
71                 if len(a) != 2:
72                         return None
73                 return a
74
75 class register:
76         def __init__(self, id, name, width):
77                 self.id = id
78                 self.name = name
79                 self.width = width
80                 self.fields = []
81
82         def add_field(self, field):
83                 self.fields.append(field)
84
85         def decode(self, value, ignore_zero):
86                 field_width = (self.width + 3) / 4
87                 name_width = max(map(lambda f: len(f.name), self.fields))
88
89                 str = "0x%0*lx [%d]\n" % (field_width, value, value)
90
91                 for field in self.fields:
92                         v = field.mask(self.width, value);
93                         if ignore_zero and v == 0:
94                                 continue
95                         desc = field.value(v)
96                         if desc is not None:
97                                 str += "%*s: 0x%x [%s]\n" \
98                                         % (name_width, field.name, v, desc)
99                         else:
100                                 str += "%*s: 0x%x\n" \
101                                         % (name_width, field.name, v)
102                 return str
103
104 def list_regs(regs):
105         for (id, r) in regs.iteritems():
106                 print "%18s : %s" % (id, r.name)
107
108 def search_regs(regs, str):
109         return dict((k, regs[k]) for k in regs \
110                         if str.lower() in regs[k].name.lower() + k.lower())
111
112 class ConfigurationError(Exception):
113         def __init__(self, file, message):
114                 self.file = file
115                 self.message = message
116
117 def parse_config(bnf, regs, file):
118         f = open(file)
119
120         tokens = bnf.parseString(f.read())
121
122         for tok in tokens:
123                 ts = tok.asList()
124                 id = ts.pop(0)
125
126                 if regs.has_key(id):
127                         raise ConfigurationError(file,
128                                 "Register %s is already defined" % id)
129
130                 # default to 64 bit registers
131                 width = 64
132                 name = None
133                 alias_id = None
134                 fields = []
135
136                 for t in ts:
137                         if t[0] == 'name':
138                                 name = t[1]
139                                 name = name.strip()
140                         elif t[0] == 'width':
141                                 width = int(t[1])
142                         elif t[0] == 'field':
143                                 f = bitfield.parse_bitfield(t[1])
144                                 if f is None:
145                                         raise ConfigurationError(file,
146                                                 "Invalid field in %s" % id)
147                                 fields.append(f)
148                         elif t[0] == 'value':
149                                 if len(fields) == 0:
150                                         raise ConfigurationError(file,
151                                                 "No field for value in %s" % id)
152                                 v = bitfield.parse_value(t[1])
153                                 if v is None:
154                                         raise ConfigurationError(file,
155                                                 "Invalid value in %s" % id)
156
157                                 fields[-1].add_value(v[0], v[1])
158                         elif t[0] == 'alias':
159                                 alias_id = t[1].strip()
160
161                 if alias_id is not None:
162                         if name is not None or fields != []:
163                                 raise ConfigurationError(file, ("Definiton " \
164                                         + "for %s is an alias, but has other " \
165                                         + "attributes") % id)
166
167                         if not regs.has_key(alias_id):
168                                 raise ConfigurationError(file, "Aliasing "
169                                         "non-existent register %s (from %s)" \
170                                         % (alias_id, id))
171
172                         regs[id] = regs[alias_id]
173                         continue
174
175                 if name is None or name == '':
176                         raise ConfigurationError(file,
177                                 "No name for entry %s" % id)
178
179                 if len(fields) == 0:
180                         raise ConfigurationError(file,
181                                 "Register %s has no fields" % id)
182
183                 r = register(id, name, width)
184                 for f in fields:
185                         r.add_field(f)
186
187                 regs[id] = r
188
189 def parse_config_dir(data, dir, fnames):
190         (bnf, regs) = data
191         for fname in fnames:
192                 full_fname = os.path.join(dir, fname)
193
194                 if os.path.isdir(full_fname):
195                         continue
196
197                 if fname.endswith('.conf'):
198                         parse_config(bnf, regs, full_fname)
199
200 def parse_all_configs(configs):
201         regs = {}
202
203         # set up the bnf to be used for each file
204         lbrack = Literal("[").suppress()
205         rbrack = Literal("]").suppress()
206         colon  = Literal(":").suppress()
207         semi   = Literal(";")
208
209         comment = semi + Optional(restOfLine)
210
211         nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
212         noncolon  = "".join([c for c in printables if c != ":"]) + " \t"
213
214         sectionDef = lbrack + Word(nonrbrack) + rbrack
215         keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
216
217         bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
218         bnf.ignore(comment)
219
220         # bundle into a single var that can be passed to os.path.walk
221         conf_data = (bnf, regs)
222
223         for conf in configs:
224                 if not os.path.exists(conf):
225                         continue
226                 if os.path.isdir(conf):
227                         os.path.walk(conf, parse_config_dir, conf_data)
228                 else:
229                         parse_config(bnf, regs, conf)
230         return regs
231
232 def usage(prog):
233         print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
234
235 def decode_value(reg, value, options):
236         try:
237                 i = long(value, 0)
238         except ValueError, e:
239                 print "error: invalid value '%s'" % value
240                 return
241
242         if i > ((1 << reg.width) - 1):
243                 print ("error: value '%s' is too large " + \
244                         "for %d-bit register '%s'") % (value, reg.width, reg.id)
245                 return
246
247         print reg.decode(i, options['non-zero'])
248
249
250 def main():
251         try:
252                 (opts, args) = getopt(sys.argv[1:], "hlns:", \
253                         ["help", "list", "non-zero", "search="])
254         except GetoptError:
255                 usage(sys.argv[0])
256                 return 1
257
258         try:
259                 regs = parse_all_configs(configs)
260         except ConfigurationError, e:
261                 print "Error parsing configuration file %s:\n\t%s" % \
262                         (e.file, e.message)
263                 return 1
264
265         if regs == {}:
266                 print "No configuration available"
267                 return 1
268
269         options = {}
270         options['non-zero'] = False
271
272         for o, a in opts:
273                 if o in ("-h", "--help"):
274                         usage(sys.argv[0])
275                         return
276
277                 if o in ("-l", "--list"):
278                         list_regs(regs)
279                         return
280
281                 if o in ("-s", "--search"):
282                         list_regs(search_regs(regs, a))
283                         return
284
285                 if o in ("-n", "--non-zero"):
286                         options['non-zero'] = True
287
288         if not args:
289                 usage(sys.argv[0])
290                 return 1
291
292         reg_id = args.pop(0)
293         if not regs.has_key(reg_id):
294                 print "No such register '%s'" % reg_id
295                 return 1
296
297         reg = regs[reg_id]
298         print "decoding as %s" % reg.name
299
300         if args:
301                 value_iter = args.__iter__()
302         else:
303                 value_iter = iter(sys.stdin.readline, '')
304                 
305         try:
306                 for value in value_iter:
307                         decode_value(reg, value.strip(), options)
308         except KeyboardInterrupt, e:
309                 pass
310
311         return 0
312
313 if __name__ == "__main__":
314         sys.exit(main())