Be a little more flexible with order strings
[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, reg):
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                                 start = reg.bit_number(int(start))
63                                 end = reg.bit_number(int(end))
64                                 bits.extend(range(start, end + 1, 1))
65                         else:
66                                 bits.append(reg.bit_number(int(s)))
67  
68                 return bitfield(bits, name)
69
70         @staticmethod
71         def parse_value(line):
72                 a = line.split(None, 1)
73                 if len(a) != 2:
74                         return None
75                 return a
76
77 class register:
78         bit_0_is_msb = 0
79         bit_0_is_lsb = 1
80
81         def __init__(self, id):
82                 self.id = id
83                 self.fields = []
84                 # set defaults
85                 self.name = None
86                 self.bit_order = self.bit_0_is_msb
87                 self.width = 64
88
89         def add_field(self, field):
90                 self.fields.append(field)
91
92         def decode(self, value, ignore_zero):
93                 field_width = (self.width + 3) / 4
94                 name_width = max(map(lambda f: len(f.name), self.fields))
95
96                 str = "0x%0*lx [%d]\n" % (field_width, value, value)
97
98                 for field in self.fields:
99                         v = field.mask(self.width, value);
100                         if ignore_zero and v == 0:
101                                 continue
102                         desc = field.value(v)
103                         if desc is not None:
104                                 str += "%*s: 0x%x [%s]\n" \
105                                         % (name_width, field.name, v, desc)
106                         else:
107                                 str += "%*s: 0x%x\n" \
108                                         % (name_width, field.name, v)
109                 return str
110         
111         def bit_number(self, number):
112                 if self.bit_order == self.bit_0_is_lsb:
113                         number = self.width - 1 - number
114                 return number
115
116 def list_regs(regs):
117         for (id, r) in regs.iteritems():
118                 print "%18s : %s" % (id, r.name)
119
120 def search_regs(regs, str):
121         return dict((k, regs[k]) for k in regs \
122                         if str.lower() in regs[k].name.lower() + k.lower())
123
124 class ConfigurationError(Exception):
125         def __init__(self, file, message):
126                 self.file = file
127                 self.message = message
128
129 def parse_config(bnf, regs, file):
130         f = open(file)
131
132         tokens = bnf.parseString(f.read())
133
134         order_map = {'bit-0-is-lsb':    register.bit_0_is_lsb,
135                         'bit-0-is-msb': register.bit_0_is_msb,
136                         'ibm':          register.bit_0_is_msb,
137                         'default':      register.bit_0_is_msb}
138
139         for tok in tokens:
140                 ts = tok.asList()
141                 id = ts.pop(0)
142
143                 if regs.has_key(id):
144                         raise ConfigurationError(file,
145                                 "Register %s is already defined" % id)
146
147                 reg = register(id)
148
149                 alias_id = None
150                 fields = []
151
152                 for t in ts:
153                         if t[0] == 'name':
154                                 name = t[1]
155                                 reg.name = name.strip()
156                         elif t[0] == 'width':
157                                 reg.width = int(t[1])
158                         elif t[0] == 'field':
159                                 f = bitfield.parse_bitfield(t[1], reg)
160                                 if f is None:
161                                         raise ConfigurationError(file,
162                                                 "Invalid field in %s" % id)
163                                 fields.append(f)
164                         elif t[0] == 'value':
165                                 if len(fields) == 0:
166                                         raise ConfigurationError(file,
167                                                 "No field for value in %s" % id)
168                                 v = bitfield.parse_value(t[1])
169                                 if v is None:
170                                         raise ConfigurationError(file,
171                                                 "Invalid value in %s" % id)
172
173                                 fields[-1].add_value(v[0], v[1])
174                         elif t[0] == 'order':
175                                 if len(fields) != 0:
176                                         raise ConfigurationError(file,
177                                                 ("bit order defined after " \
178                                                 + "fields in %s") % id)
179
180                                 order_str = t[1].strip().lower()
181                                 order_str = order_str.replace(' ', '-')
182
183                                 if order_str not in order_map.keys():
184                                         raise ConfigurationError(file,
185                                                 "Invalid bit order %s in %s" % \
186                                                 (order_str, id))
187                                 reg.bit_order = order_map[order_str]
188                                 
189                         elif t[0] == 'alias':
190                                 alias_id = t[1].strip()
191
192                 if alias_id is not None:
193                         if reg.name is not None or fields != []:
194                                 raise ConfigurationError(file, ("Definiton " \
195                                         + "for %s is an alias, but has other " \
196                                         + "attributes") % id)
197
198                         if not regs.has_key(alias_id):
199                                 raise ConfigurationError(file, "Aliasing "
200                                         "non-existent register %s (from %s)" \
201                                         % (alias_id, id))
202
203                         reg = regs[alias_id]
204                         continue
205
206                 if reg.name is None or reg.name == '':
207                         raise ConfigurationError(file,
208                                 "No name for entry %s" % id)
209
210                 if len(fields) == 0:
211                         raise ConfigurationError(file,
212                                 "Register %s has no fields" % id)
213
214                 for f in fields:
215                         reg.add_field(f)
216
217                 regs[id] = reg
218
219 def parse_config_dir(data, dir, fnames):
220         (bnf, regs) = data
221         for fname in fnames:
222                 full_fname = os.path.join(dir, fname)
223
224                 if os.path.isdir(full_fname):
225                         continue
226
227                 if fname.endswith('.conf'):
228                         parse_config(bnf, regs, full_fname)
229
230 def parse_all_configs(configs):
231         regs = {}
232
233         # set up the bnf to be used for each file
234         lbrack = Literal("[").suppress()
235         rbrack = Literal("]").suppress()
236         colon  = Literal(":").suppress()
237         semi   = Literal(";")
238
239         comment = semi + Optional(restOfLine)
240
241         nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
242         noncolon  = "".join([c for c in printables if c != ":"]) + " \t"
243
244         sectionDef = lbrack + Word(nonrbrack) + rbrack
245         keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
246
247         bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
248         bnf.ignore(comment)
249
250         # bundle into a single var that can be passed to os.path.walk
251         conf_data = (bnf, regs)
252
253         for conf in configs:
254                 if not os.path.exists(conf):
255                         continue
256                 if os.path.isdir(conf):
257                         os.path.walk(conf, parse_config_dir, conf_data)
258                 else:
259                         parse_config(bnf, regs, conf)
260         return regs
261
262 def usage(prog):
263         print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
264
265 def decode_value(reg, value, options):
266         try:
267                 i = long(value, 0)
268         except ValueError, e:
269                 print "error: invalid value '%s'" % value
270                 return
271
272         if i > ((1 << reg.width) - 1):
273                 print ("error: value '%s' is too large " + \
274                         "for %d-bit register '%s'") % (value, reg.width, reg.id)
275                 return
276
277         print reg.decode(i, options['non-zero'])
278
279
280 def main():
281         try:
282                 (opts, args) = getopt(sys.argv[1:], "hlns:", \
283                         ["help", "list", "non-zero", "search="])
284         except GetoptError:
285                 usage(sys.argv[0])
286                 return 1
287
288         try:
289                 regs = parse_all_configs(configs)
290         except ConfigurationError, e:
291                 print "Error parsing configuration file %s:\n\t%s" % \
292                         (e.file, e.message)
293                 return 1
294
295         if regs == {}:
296                 print "No configuration available"
297                 return 1
298
299         options = {}
300         options['non-zero'] = False
301
302         for o, a in opts:
303                 if o in ("-h", "--help"):
304                         usage(sys.argv[0])
305                         return
306
307                 if o in ("-l", "--list"):
308                         list_regs(regs)
309                         return
310
311                 if o in ("-s", "--search"):
312                         list_regs(search_regs(regs, a))
313                         return
314
315                 if o in ("-n", "--non-zero"):
316                         options['non-zero'] = True
317
318         if not args:
319                 usage(sys.argv[0])
320                 return 1
321
322         reg_id = args.pop(0)
323         if not regs.has_key(reg_id):
324                 print "No such register '%s'" % reg_id
325                 return 1
326
327         reg = regs[reg_id]
328         print "decoding as %s" % reg.name
329
330         if args:
331                 value_iter = args.__iter__()
332         else:
333                 value_iter = iter(sys.stdin.readline, '')
334                 
335         try:
336                 for value in value_iter:
337                         decode_value(reg, value.strip(), options)
338         except KeyboardInterrupt, e:
339                 pass
340
341         return 0
342
343 if __name__ == "__main__":
344         sys.exit(main())