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
7 # Documentation and updates at: http://ozlabs.org/~jk/code/bitfield
12 from pyparsing import Literal, Word, ZeroOrMore, Group, Dict, Optional, \
13 printables, ParseException, restOfLine
14 from getopt import getopt, GetoptError
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 = [os.path.join(os.getenv("HOME"), ".bitfield.conf"),
19 os.path.join(os.getenv("HOME"), ".bitfield.d"),
20 "/etc/bitfield.d", "/etc/bitfield", ]
23 def __init__(self, bits, name):
31 def add_value(self, value, description):
32 self.values[int(value)] = description
34 def mask(self, reg_width, value):
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
46 def value(self, value):
47 if value in self.values:
48 return self.values[value]
52 def parse_bitfield(line):
53 a = line.split(None, 1)
59 for s in range_str.split(','):
61 (start, end) = s.split(':')
62 bits.extend(range(int(start), int(end) + 1, 1))
66 return bitfield(bits, name)
69 def parse_value(line):
70 a = line.split(None, 1)
76 def __init__(self, id, name, width):
82 def add_field(self, field):
83 self.fields.append(field)
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))
89 str = "0x%0*lx [%d]\n" % (field_width, value, value)
91 for field in self.fields:
92 v = field.mask(self.width, value);
93 if ignore_zero and v == 0:
97 str += "%*s: 0x%x [%s]\n" \
98 % (name_width, field.name, v, desc)
100 str += "%*s: 0x%x\n" \
101 % (name_width, field.name, v)
105 for (id, r) in regs.iteritems():
106 print "%18s : %s" % (id, r.name)
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())
112 class ConfigurationError(Exception):
113 def __init__(self, file, message):
115 self.message = message
117 def parse_config(bnf, regs, file):
120 tokens = bnf.parseString(f.read())
127 raise ConfigurationError(file,
128 "Register %s is already defined" % id)
130 # default to 64 bit registers
139 elif t[0] == 'width':
141 elif t[0] == 'field':
142 f = bitfield.parse_bitfield(t[1])
144 raise ConfigurationError(file,
145 "Invalid field in %s" % id)
147 elif t[0] == 'value':
149 raise ConfigurationError(file,
150 "No field for value in %s" % id)
151 v = bitfield.parse_value(t[1])
153 raise ConfigurationError(file,
154 "Invalid value in %s" % id)
156 fields[-1].add_value(v[0], v[1])
158 if name is None or name == '':
159 raise ConfigurationError(file,
160 "No name for entry %s" % id)
163 raise ConfigurationError(file,
164 "Register %s has no fields" % id)
166 r = register(id, name, width)
172 def parse_config_dir(data, dir, fnames):
175 full_fname = os.path.join(dir, fname)
177 if os.path.isdir(full_fname):
180 if fname.endswith('.conf'):
181 parse_config(bnf, regs, full_fname)
183 def parse_all_configs(configs):
186 # set up the bnf to be used for each file
187 lbrack = Literal("[").suppress()
188 rbrack = Literal("]").suppress()
189 colon = Literal(":").suppress()
192 comment = semi + Optional(restOfLine)
194 nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
195 noncolon = "".join([c for c in printables if c != ":"]) + " \t"
197 sectionDef = lbrack + Word(nonrbrack) + rbrack
198 keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
200 bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
203 # bundle into a single var that can be passed to os.path.walk
204 conf_data = (bnf, regs)
207 if not os.path.exists(conf):
209 if os.path.isdir(conf):
210 os.path.walk(conf, parse_config_dir, conf_data)
212 parse_config(bnf, regs, conf)
216 print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
218 def decode_value(reg, value, options):
221 except ValueError, e:
222 print "error: invalid value '%s'" % value
225 if i > ((1 << reg.width) - 1):
226 print ("error: value '%s' is too large " + \
227 "for %d-bit register '%s'") % (value, reg.width, reg.id)
230 print reg.decode(i, options['non-zero'])
235 (opts, args) = getopt(sys.argv[1:], "hlns:", \
236 ["help", "list", "non-zero", "search="])
242 regs = parse_all_configs(configs)
243 except ConfigurationError, e:
244 print "Error parsing configuration file %s:\n\t%s" % \
249 print "No configuration available"
253 options['non-zero'] = False
256 if o in ("-h", "--help"):
260 if o in ("-l", "--list"):
264 if o in ("-s", "--search"):
265 list_regs(search_regs(regs, a))
268 if o in ("-n", "--non-zero"):
269 options['non-zero'] = True
276 if not regs.has_key(reg_id):
277 print "No such register '%s'" % reg_id
281 print "decoding as %s" % reg.name
284 value_iter = args.__iter__()
286 value_iter = iter(sys.stdin.readline, '')
289 for value in value_iter:
290 decode_value(reg, value.strip(), options)
291 except KeyboardInterrupt, e:
296 if __name__ == "__main__":