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"), ".bitfields.conf"),
19 os.path.join(os.getenv("HOME"), ".bitfields.d")]
22 def __init__(self, start_bit, end_bit, name):
23 self.start_bit = start_bit
24 self.end_bit = end_bit
35 return 1 + self.end_bit - self.start_bit
37 def add_value(self, value, description):
38 self.values[int(value)] = description
40 def mask(self, reg_width, value):
41 shift = (reg_width - 1) - self.end_bit
42 return (((2 ** self.width() - 1) << (shift))
45 def value(self, value):
46 if value in self.values:
47 return self.values[value]
51 def parse_bitfield(line):
52 a = line.split(None, 1)
58 if range_str.find(':') != -1:
59 r = range_str.split(":")
60 range = (int(r[0]),int(r[1]))
62 range = (int(range_str),int(range_str))
64 return bitfield(range[0], range[1], name)
67 def parse_value(line):
68 a = line.split(None, 1)
74 def __init__(self, id, name, width):
80 def add_field(self, field):
81 self.fields.append(field)
83 def decode(self, value, ignore_zero):
84 field_width = (self.width + 3) / 4
85 name_width = max(map(lambda f: len(f.name), self.fields))
87 str = "0x%0*lx [%d]\n" % (field_width, value, value)
89 for field in self.fields:
90 v = field.mask(self.width, value);
91 if ignore_zero and v == 0:
95 str += "%*s: 0x%x [%s]\n" \
96 % (name_width, field.name, v, desc)
98 str += "%*s: 0x%x\n" \
99 % (name_width, field.name, v)
103 for (id, r) in regs.iteritems():
104 print "%18s : %s" % (id, r.name)
106 def search_regs(regs, str):
107 return dict((k, regs[k]) for k in regs \
108 if str.lower() in regs[k].name.lower() + k.lower())
110 class ConfigurationError(Exception):
111 def __init__(self, file, message):
113 self.message = message
115 def parse_config(bnf, regs, file):
118 tokens = bnf.parseString(f.read())
125 raise ConfigurationError(file,
126 "Register %s is already defined" % id)
128 # default to 64 bit registers
137 elif t[0] == 'width':
139 elif t[0] == 'field':
140 f = bitfield.parse_bitfield(t[1])
142 raise ConfigurationError(file,
143 "Invalid field in %s" % id)
145 elif t[0] == 'value':
147 raise ConfigurationError(file,
148 "No field for value in %s" % id)
149 v = bitfield.parse_value(t[1])
151 raise ConfigurationError(file,
152 "Invalid value in %s" % id)
154 fields[-1].add_value(v[0], v[1])
156 if name is None or name == '':
157 raise ConfigurationError(file,
158 "No name for entry %s" % id)
161 raise ConfigurationError(file,
162 "Register %s has no fields" % id)
164 r = register(id, name, width)
170 def parse_config_dir(data, dir, fnames):
173 full_fname = os.path.join(dir, fname)
175 if os.path.isdir(full_fname):
178 if fname.endswith('.conf'):
179 parse_config(bnf, regs, full_fname)
181 def parse_all_configs(configs):
184 # set up the bnf to be used for each file
185 lbrack = Literal("[").suppress()
186 rbrack = Literal("]").suppress()
187 colon = Literal(":").suppress()
190 comment = semi + Optional(restOfLine)
192 nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
193 noncolon = "".join([c for c in printables if c != ":"]) + " \t"
195 sectionDef = lbrack + Word(nonrbrack) + rbrack
196 keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
198 bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
201 # bundle into a single var that can be passed to os.path.walk
202 conf_data = (bnf, regs)
205 if not os.path.exists(conf):
207 if os.path.isdir(conf):
208 os.path.walk(conf, parse_config_dir, conf_data)
210 parse_config(bnf, regs, conf)
214 print "Usage: %s <-l> | <-s pattern> | [-n] register [value...]" % prog
216 def decode_value(reg, value, options):
219 except ValueError, e:
220 print "error: invalid value '%s'" % value
223 if i > ((1 << reg.width) - 1):
224 print ("error: value '%s' is too large " + \
225 "for %d-bit register '%s'") % (value, reg.width, reg.id)
228 print reg.decode(i, options.has_key('non_zero'))
233 (opts, args) = getopt(sys.argv[1:], "hlns:", \
234 ["help", "list", "non-zero", "search="])
240 regs = parse_all_configs(configs)
241 except ConfigurationError, e:
242 print "Error parsing configuration file %s:\n\t%s" % \
247 print "No configuration available"
251 options['non-zero'] = False
254 if o in ("-h", "--help"):
258 if o in ("-l", "--list"):
262 if o in ("-s", "--search"):
263 list_regs(search_regs(regs, a))
266 if o in ("-n", "--non-zero"):
267 options['non-zero'] = True
274 if not regs.has_key(reg_id):
275 print "No such register '%s'" % reg_id
279 print "decoding as %s" % reg.name
282 value_iter = args.__iter__()
284 value_iter = iter(sys.stdin.readline, '')
287 for value in value_iter:
288 decode_value(reg, value.strip(), options)
289 except KeyboardInterrupt, e:
294 if __name__ == "__main__":