OpenCores
URL https://opencores.org/ocsvn/light52/light52/trunk

Subversion Repositories light52

[/] [light52/] [trunk/] [tools/] [build_rom/] [src/] [build_rom.py] - Blame information for rev 22

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 4 ja_rd
#!/usr/bin/env python
2
"""
3
build_rom.py: Create VHDL package with ROM initialization constant from
4
Intel-HEX object code file.
5 22 ja_rd
Please use with --help to get some brief usage instructions.
6 4 ja_rd
"""
7
__author__ = "Jose A. Ruiz"
8
__license__ = "LGPL"
9
 
10
 
11
"""
12
Please see the usage instructions and the comments for function 'main'.
13
"""
14
 
15
 
16
import sys
17
import getopt
18
 
19
 
20
 
21
def usage():
22
    """Print usage instructions"""
23
    print ""
24
    print "usage:"
25
    print "python build_rom.py [arguments]\n"
26
    print "Builds VHDL ROM constant from template and Intel HEX object file.\n"
27
    print "ALL of the following arguments should be given, in any order:"
28
    print "{f|file} <filename>        Object code file name"
29 22 ja_rd
    print ""
30
    print "Additionally, any of these arguments can be given:"
31
    print "{h|help}                   Show help string and exit"
32
    print "{c|constant} <name>        Name of target VHDL object code constant"
33 4 ja_rd
    print "{p|package} <name>         Name of target VHDL package"
34 22 ja_rd
    print "{n|name} <name>            Name of project (used only in comments)"
35 4 ja_rd
    print "{o|output} <filename>      Target VHDL file name"
36 22 ja_rd
    print "{xcode} <number>           Size of XCODE memory in bytes"
37
    print "         (defaults to 2048)"
38
    print "{xdata} <number>           Size of XDATA memory in bytes"
39
    print "         (defaults to 0)"
40 4 ja_rd
    print "{v|vhdl} <filename>        VHDL template"
41
    print "         (defaults to templates/obj_code_kg_template.vhdl)"
42
    print "{i|indent} <number>        Indentation in VHDL tables (decimal)"
43
    print "         (defaults to 4)"
44
 
45
 
46 22 ja_rd
 
47 4 ja_rd
def help():
48
    """Print help message a bit longer than usage message."""
49
    print "\nPurpose:\n"
50 22 ja_rd
    print "Builds initialization package for Light52 MCU core."
51
    print "The object code bytes are converted to VHDL strings and then inserted"
52
    print "into the vhdl template, in place of tag @code_bytes@.\n"
53 4 ja_rd
    print "Template tags are replaced as follows:"
54
    print "@obj_pkg_name@        : Name of package in target vhdl file."
55 22 ja_rd
    print "@const_name@          : Name of object code constant (VHDL table)."
56 4 ja_rd
    print "@obj_size@            : Total size of code table in bytes."
57 22 ja_rd
    print "@obj_bytes@           : Array of object code bytes."
58
    print "@project_name@        : Project name."
59 4 ja_rd
    print "@xcode_size@          : Size of XCODE memory."
60
    print "@xdata_size@          : Size of XDATA memory."
61
 
62
def parse_hex_line(line):
63
    """Parse code line in HEX object file."""
64
    line = line.strip()
65
    slen = int(line[1:3],16)
66
    sloc = int(line[3:7],16)
67
    stype = line[7:9]
68
    sdata = line[9:len(line)-2]
69
    schk = int(line[len(line)-2:],16)
70
 
71
    csum = slen + int(sloc / 256) + (sloc % 256) + int(stype,16)
72
    bytes = [0, ] * slen
73
    for i in range(slen):
74
        sbyte = int(sdata[i*2:i*2+2],16)
75
        bytes[i] = sbyte;
76
        csum = csum + sbyte
77
 
78
    csum = ~csum
79
    csum = csum + 1
80
    csum = csum % 256
81
    if csum != schk:
82
        return (None, None)
83
 
84
    return (sloc, bytes)
85
 
86
 
87
def read_ihex_file(ihex_filename):
88
    """
89
    Read Intel HEX file into a 64KB array.
90
    The file is assumed not to have any object code outside the 64K boundary.
91
    Return the 64K array plus the size and bounds of the read data.
92
    """
93
 
94
    # CODE array, initialized to 64K of zeros...
95
    xcode = [0, ] * 65536
96
    # ...and code boundaries, initialized out of range.
97
    bottom = 100000
98
    top = -1
99
    (xcode, top, bottom)
100
 
101
    # Read the whole file to a list of lines...
102
    fin = open(ihex_filename, "r")
103
    ihex_lines = fin.readlines()
104
    fin.close()
105
 
106
    # ...and parse the lines one by one.
107
    total_bytes = 0
108
    for line in ihex_lines:
109
        (address, bytes) = parse_hex_line(line)
110
        if address == None:
111
            print "Checksum error!"
112
            sys.exit(1)
113
        total_bytes = total_bytes + len(bytes)
114
        for i in range(len(bytes)):
115
            xcode[address + i] = bytes[i]
116
 
117
        if address < bottom:
118
            bottom = address
119
 
120
        if (address + len(bytes)) > top:
121
            top = (address + len(bytes))
122
 
123
    print "Read %d bytes from file '%s'" % (total_bytes, ihex_filename)
124
    print "Code range %04xh to %04xh" % (bottom, top)
125
    return (xcode, total_bytes, bottom, top)
126
 
127
 
128
def build_vhdl_code(params, xcode, obj_size):
129
    """
130
    Read VHDL template file and replace all the tags with the values given in
131
    the command line parameters.
132
    Return the new file contents as a string.
133
    """
134
 
135
    # The resulting VHDL text will be stored here.
136
    vhdl_code = ""
137
 
138
 
139
    # Open file and read it into a list of lines.
140
    fin = open(params['template'], "r")
141
    lines = fin.readlines()
142
    fin.close()
143
 
144
    # Now process the template lines one by one.
145
    for line in lines:
146
        line = line.strip()
147
 
148
        if line.rfind("@obj_bytes@") >= 0:
149
            # insert object code as list of byte literals.
150
            obj_str = "    "
151
            for i in range(obj_size):
152
                if i != (obj_size-1):
153
                    sbyte = "X\"%02x\", " % xcode[i]
154
                else:
155
                    sbyte = "X\"%02x\" " % xcode[i]
156
                obj_str = obj_str + sbyte
157
                if (i % 8) == 7:
158
                    obj_str = obj_str + "\n    "
159
 
160
            line = line.replace("@obj_bytes@",obj_str)
161
 
162
        elif line.rfind("@obj_size@") >= 0:
163
            # Insert object code size (not necessarily equal to xcode_size)
164
            line = line.replace("@obj_size@","%d" % (obj_size-1))
165
 
166
        elif line.rfind("@xcode_size@") >= 0:
167
            # Insert XCODE memory
168
            line = line.replace("@xcode_size@","%d" % (params['xcode_size']))
169
 
170
        elif line.rfind("@xdata_size@") >= 0:
171
            # Insert XDATA memory
172
            line = line.replace("@xdata_size@","%d" % (params['xdata_size']))
173
 
174
        elif line.rfind("@obj_pkg_name@") >= 0:
175
            # Insert package name: hardwired
176
            line = line.replace("@obj_pkg_name@",params['package'])
177
 
178
        elif line.rfind("@project_name@") >= 0:
179
            # Insert project name 
180
            line = line.replace("@project_name@",params['project'])
181
 
182
 
183
        vhdl_code = vhdl_code + line + "\n"
184
 
185
    return vhdl_code
186
 
187
 
188
def main(argv):
189
    """Main body of the program."""
190
 
191
    # Parse command line parameters using GetOpt 
192
    try:
193
        opts, args = getopt.getopt(argv, "hf:n:p:c:o:i:v:",
194
        ["help", "file=", "name=", "package=", "constant=",
195
         "output=", "indent=", "vhdl=", "xcode=", "xdata=" ])
196
    except getopt.GetoptError, err:
197
        print ""
198
        print err
199
        usage()
200
        sys.exit(2)
201
 
202
    # Command line parameters, initialized to their default values
203
    params = {'project':    '<unknown>',
204
              'package':    'obj_code_pkg',
205
              'indent':     4,
206
              'constant':   'obj_code',
207
              'target':     'obj_code_pkg.vhdl',
208
              'hex':        '',
209
              'xcode_size': 2048,
210
              'xdata_size': 0,
211
              'template':   "./templates/obj_code_pkg_template.vhdl"
212
              }
213
 
214
 
215
    # Parse coommand line parameters
216
    for opt, arg in opts:
217
        if opt in ("-h", "--help"):
218
            usage()
219
            help()
220
            exit(1)
221
        if opt in ("-v", "--vhdl"):
222
            params['template'] = arg
223
        elif opt in ("-o", "--output"):
224
            params['target'] = arg
225
        elif opt in ("-c", "--constant"):
226
            params['constant'] = arg
227
        elif opt in ("-f", "--file"):
228
            params['hex'] = arg
229
        elif opt in ("-p", "--package"):
230
            params['package'] = arg
231
        elif opt in ("-n", "--name"):
232
            params['project'] = arg
233
        elif opt in ("-i", "--indent"):
234
            params['indent'] = int(arg)
235
        elif opt in ("--xcode"):
236
            params['xcode_size'] = int(arg)
237
        elif opt in ("--xdata"):
238
            params['xdata_size'] = int(arg)
239
 
240 22 ja_rd
    # Ok, now read and parse the input Intel HEX object code file.
241 4 ja_rd
    if params['hex']:
242
        (xcode, total_bytes, bottom, top) = read_ihex_file(params['hex']);
243
    else:
244
        print "Object HEX file name missing.";
245
        usage()
246
        return 1
247
 
248
 
249 22 ja_rd
    # Make sure the object code fits into the implemented XCODE space.
250 4 ja_rd
    # If it doesn't, print a warning and let the user deal with it.
251
    # Assuming that XCODE starts at address zero -- that's how the core works.
252
    if params['xcode_size'] < top:
253
        print "\nWARNING: Object code does not fit XCODE space!\n"
254
 
255
 
256
    # Build the package source...
257
    vhdl_code = build_vhdl_code(params, xcode, top);
258
 
259
    # ...and write it to the target file.
260
    fout = None
261
    try:
262
        fout = open(params['target'], "w")
263
        fout.write(vhdl_code)
264
        fout.close()
265
        print "VHDL code table written to %s" % params['target']
266
    except:
267
        print "Trouble opening %s for output" % params['target']
268
    finally:
269
        if fout: fout.close()
270
 
271
 
272
if __name__ == "__main__":
273
    main(sys.argv[1:])
274
    sys.exit(0)
275
 
276
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.