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, name, width):
79 def add_field(self, field,):
80 self.fields.append(field)
82 def decode(self, value):
83 field_width = (self.width + 3) / 4
84 name_width = max(map(lambda f: len(f.name), self.fields))
85 str = "0x%0*lx [%d]\n" % (field_width, value, value)
86 for field in self.fields:
87 v = field.mask(self.width, value);
90 str += "%*s: 0x%s [%s]\n" \
91 % (name_width, field.name, v, desc)
93 str += "%*s: 0x%x\n" \
94 % (name_width, field.name, v)
98 for (id, r) in regs.iteritems():
99 print "%18s : %s" % (id, r.name)
101 def search_regs(regs, str):
102 return dict((k, regs[k]) for k in regs \
103 if str.lower() in regs[k].name.lower() + k.lower())
105 class ConfigurationError(Exception):
106 def __init__(self, file, message):
108 self.message = message
110 def parse_config(bnf, regs, file):
113 tokens = bnf.parseString("".join(f.readlines()))
120 raise ConfigurationError(file,
121 "Register %s is already defined" % id)
123 # default to 64 bit registers
132 elif t[0] == 'width':
134 elif t[0] == 'field':
135 f = bitfield.parse_bitfield(t[1])
137 raise ConfigurationError(file,
138 "Invalid field in %s" % id)
140 elif t[0] == 'value':
142 raise ConfigurationError(file,
143 "No field for value in %s" % id)
144 v = bitfield.parse_value(t[1])
146 raise ConfigurationError(file,
147 "Invalid value in %s" % id)
149 fields[-1].add_value(v[0], v[1])
151 if name is None or name == '':
152 raise ConfigurationError(file,
153 "No name for entry %s" % id)
156 raise ConfigurationError(file,
157 "Register %s has no fields" % id)
159 r = register(name, width)
165 def parse_config_dir(data, dir, fnames):
168 full_fname = os.path.join(dir, fname)
170 if os.path.isdir(full_fname):
173 if fname.endswith('.conf'):
174 parse_config(bnf, regs, full_fname)
176 def parse_all_configs(configs):
179 # set up the bnf to be used for each file
180 lbrack = Literal("[").suppress()
181 rbrack = Literal("]").suppress()
182 colon = Literal(":").suppress()
185 comment = semi + Optional(restOfLine)
187 nonrbrack = "".join([c for c in printables if c != "]"]) + " \t"
188 noncolon = "".join([c for c in printables if c != ":"]) + " \t"
190 sectionDef = lbrack + Word(nonrbrack) + rbrack
191 keyDef = ~lbrack + Word(noncolon) + colon + restOfLine
193 bnf = Dict(ZeroOrMore(Group(sectionDef + ZeroOrMore(Group(keyDef)))))
196 # bundle into a single var that can be passed to os.path.walk
197 conf_data = (bnf, regs)
200 if not os.path.exists(conf):
202 if os.path.isdir(conf):
203 os.path.walk(conf, parse_config_dir, conf_data)
205 parse_config(bnf, regs, conf)
209 print "Usage: %s <-l> | <-s pattern> | register [value...]" % prog
213 (opts, args) = getopt(sys.argv[1:], "hls:", \
214 ["help", "list", "search="])
220 regs = parse_all_configs(configs)
221 except ConfigurationError, e:
222 print "Error parsing configuration file %s:\n\t%s" % \
227 print "No configuration available"
231 if o in ("-h", "--help"):
235 if o in ("-l", "--list"):
239 if o in ("-s", "--search"):
240 list_regs(search_regs(regs, a))
249 if not regs.has_key(reg_id):
250 print "No such register '%s'" % reg_id
254 print "decoding as %s" % r.name
260 values = sys.stdin.readlines()
261 except KeyboardInterrupt, e:
265 i = long(value.strip(), 0)
270 if __name__ == "__main__":