Add order: config option to define the bit ordering of register 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, 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                                 if order_str not in order_map.keys():
182                                         raise ConfigurationError(file,
183                                                 "Invalid bit order %s in %s" % \
184                                                 (order_str, id))
185                                 reg.bit_order = order_map[order_str]
186                                 
187                         elif t[0] == 'alias':
188                                 alias_id = t[1].strip()
189
190                 if alias_id is not None:
191                         if reg.name is not None or fields != []:
192                                 raise ConfigurationError(file, ("Definiton " \
193                                         + "for %s is an alias, but has other " \
194                                         + "attributes") % id)
195
196                         if not regs.has_key(alias_id):
197                                 raise ConfigurationError(file, "Aliasing "
198                                         "non-existent register %s (from %s)" \
199                                         % (alias_id, id))
200
201                         reg = regs[alias_id]
202                         continue
203
204                 if reg.name is None or reg.name == '':
205                         raise ConfigurationError(file,
206                                 "No name for entry %s" % id)
207
208                 if len(fields) == 0:
209                         raise ConfigurationError(file,
210                                 "Register %s has no fields" % id)
211
212                 for f in fields:
213                         reg.add_field(f)
214
215                 regs[id] = reg
216
217 def parse_config_dir(data, dir, fnames):
218         (bnf, regs) = data
219         for fname in fnames:
220                 full_fname = os.path.join(dir, fname)
221
222                 if os.path.isdir(full_fname):
223                         continue
224
225                 if fname.endswith('.conf'):
226                         parse_config(bnf, regs, full_fname)
227
228 def parse_all_configs(configs):
229         regs = {}
230
231         # set up the bnf to be used for each file
232         lbrack = Literal("[").suppress()
233         rbrack = Literal("]").suppress()
234         colon  = Literal(":").suppress()
235         semi   = Literal(";")
236
237         comment = semi + Optional(restOfLine)
238
239         nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
240         noncolon  = "".join([c for c in printables if c != ":"]) + " \t"
241
242         sectionDef = lbrack + Word(nonrbrack) + rbrack
243         keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
244
245         bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
246         bnf.ignore(comment)
247
248         # bundle into a single var that can be passed to os.path.walk
249         conf_data = (bnf, regs)
250
251         for conf in configs:
252                 if not os.path.exists(conf):
253                         continue
254                 if os.path.isdir(conf):
255                         os.path.walk(conf, parse_config_dir, conf_data)
256                 else:
257                         parse_config(bnf, regs, conf)
258         return regs
259
260 def usage(prog):
261         print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
262
263 def decode_value(reg, value, options):
264         try:
265                 i = long(value, 0)
266         except ValueError, e:
267                 print "error: invalid value '%s'" % value
268                 return
269
270         if i > ((1 << reg.width) - 1):
271                 print ("error: value '%s' is too large " + \
272                         "for %d-bit register '%s'") % (value, reg.width, reg.id)
273                 return
274
275         print reg.decode(i, options['non-zero'])
276
277
278 def main():
279         try:
280                 (opts, args) = getopt(sys.argv[1:], "hlns:", \
281                         ["help", "list", "non-zero", "search="])
282         except GetoptError:
283                 usage(sys.argv[0])
284                 return 1
285
286         try:
287                 regs = parse_all_configs(configs)
288         except ConfigurationError, e:
289                 print "Error parsing configuration file %s:\n\t%s" % \
290                         (e.file, e.message)
291                 return 1
292
293         if regs == {}:
294                 print "No configuration available"
295                 return 1
296
297         options = {}
298         options['non-zero'] = False
299
300         for o, a in opts:
301                 if o in ("-h", "--help"):
302                         usage(sys.argv[0])
303                         return
304
305                 if o in ("-l", "--list"):
306                         list_regs(regs)
307                         return
308
309                 if o in ("-s", "--search"):
310                         list_regs(search_regs(regs, a))
311                         return
312
313                 if o in ("-n", "--non-zero"):
314                         options['non-zero'] = True
315
316         if not args:
317                 usage(sys.argv[0])
318                 return 1
319
320         reg_id = args.pop(0)
321         if not regs.has_key(reg_id):
322                 print "No such register '%s'" % reg_id
323                 return 1
324
325         reg = regs[reg_id]
326         print "decoding as %s" % reg.name
327
328         if args:
329                 value_iter = args.__iter__()
330         else:
331                 value_iter = iter(sys.stdin.readline, '')
332                 
333         try:
334                 for value in value_iter:
335                         decode_value(reg, value.strip(), options)
336         except KeyboardInterrupt, e:
337                 pass
338
339         return 0
340
341 if __name__ == "__main__":
342         sys.exit(main())