提交 b4357384 编写于 作者: G Grissiom

romfs: rewrite mkromfs.py

上级 e882597f
#!/usr/bin/env python
import sys import sys
import os import os
import string
import struct
basename = '' from collections import namedtuple
output = '' import StringIO
sep = os.sep
import argparse
def mkromfs_output(out): parser = argparse.ArgumentParser()
# print '%s' % out, parser.add_argument('rootdir', type=str, help='the path to rootfs')
output.write(out) parser.add_argument('output', type=argparse.FileType('wb'), nargs='?', help='output file name')
parser.add_argument('--dump', action='store_true', help='dump the fs hierarchy')
def mkromfs_file(filename, arrayname): parser.add_argument('--binary', action='store_true', help='output binary file')
f = file(filename, "rb") parser.add_argument('--addr', default='0', help='set the base address of the binary file, default to 0.')
arrayname = arrayname.replace('.', '_')
arrayname = arrayname.replace('-', '_') class File(object):
mkromfs_output('const static unsigned char %s[] = {\n' % arrayname) def __init__(self, name):
self._name = name
count = 0 self._data = open(name, 'rb').read()
while True:
byte = f.read(1) @property
def name(self):
if len(byte) != 1: return self._name
break
@property
mkromfs_output('0x%02x,' % ord(byte)) def c_name(self):
return '_' + self._name.replace('.', '_')
count = count + 1
if count == 16: @property
count = 0 def bin_name(self):
mkromfs_output('\n') # Pad to 4 bytes boundary with \0
pad_len = 4
if count == 0: bn = self._name + '\0' * (pad_len - len(self._name) % pad_len)
mkromfs_output('};\n\n') return bn
else:
mkromfs_output('\n};\n\n') def c_data(self, prefix=''):
'''Get the C code represent of the file content.'''
f.close() head = 'static const rt_uint8_t %s[] = {\n' % \
(prefix + self.c_name)
def mkromfs_dir(dirname, is_root = False): tail = '\n};'
list = os.listdir(dirname) return head + ','.join(('0x%02x' % ord(i) for i in self._data)) + tail
path = os.path.abspath(dirname)
@property
# make for directory def entry_size(self):
for item in list: return len(self._data)
fullpath = os.path.join(path, item)
if os.path.isdir(fullpath): def bin_data(self, base_addr=0x0):
# if it is an empty directory, ignore it return bytes(self._data)
l = os.listdir(fullpath)
if len(l): def dump(self, indent=0):
mkromfs_dir(fullpath) print '%s%s' % (' ' * indent, self._name)
# make for files class Folder(object):
for item in list: bin_fmt = struct.Struct('IIII')
fullpath = os.path.join(path, item) bin_item = namedtuple('dirent', 'type, name, data, size')
if os.path.isfile(fullpath):
subpath = fullpath[len(basename):] def __init__(self, name):
array = subpath.split(sep) self._name = name
arrayname = string.join(array, '_') self._children = []
mkromfs_file(fullpath, arrayname)
@property
subpath = path[len(basename):] def name(self):
dir = subpath.split(sep) return self._name
direntname = string.join(dir, '_')
if is_root: @property
mkromfs_output('const struct romfs_dirent _root_dirent[] = {\n') def c_name(self):
else: # add _ to avoid conflict with C key words.
mkromfs_output(('const static struct romfs_dirent %s[] = {\n' % direntname)) return '_' + self._name
for item in list: @property
fullpath = os.path.join(path, item) def bin_name(self):
fn = fullpath[len(dirname):] # Pad to 4 bytes boundary with \0
if fn[0] == sep: pad_len = 4
fn = fn[1:] bn = self._name + '\0' * (pad_len - len(self._name) % pad_len)
fn = fn.replace('\\', '/') return bn
subpath = fullpath[len(basename):] def walk(self):
items = subpath.split(sep) # os.listdir will return unicode list if the argument is unicode.
item_name = string.join(items, '_') # TODO: take care of the unicode names
item_name = item_name.replace('.', '_') for ent in os.listdir(u'.'):
item_name = item_name.replace('-', '_') if os.path.isdir(ent):
subpath = subpath.replace('\\', '/') cwd = os.getcwdu()
if subpath[0] == '/': d = Folder(ent)
subpath = subpath[1:] # depth-first
os.chdir(os.path.join(cwd, ent))
if not os.path.isfile(fullpath): d.walk()
l = os.listdir(fullpath) # restore the cwd
if len(l): os.chdir(cwd)
mkromfs_output(('\t{ROMFS_DIRENT_DIR, "%s", (rt_uint8_t*) %s, sizeof(%s)/sizeof(%s[0])},\n' % (fn, item_name, item_name, item_name))) self._children.append(d)
else:
self._children.append(File(ent))
def sort(self):
def _sort(x, y):
if x.name == y.name:
return 0
elif x.name > y.name:
return 1
else:
return -1
self._children.sort(cmp=_sort)
# sort recursively
for c in self._children:
if isinstance(c, Folder):
c.sort()
def dump(self, indent=0):
print '%s%s' % (' ' * indent, self._name)
for c in self._children:
c.dump(indent + 1)
def c_data(self, prefix=''):
'''get the C code represent of the folder.
It is recursive.'''
# make the current dirent
# static is good. Only root dirent is global visible.
dhead = 'static const struct romfs_dirent %s[] = {\n' % (prefix + self.c_name)
dtail = '\n};'
body_fmt = ' {{{type}, "{name}", (rt_uint8_t *){data}, sizeof({data})/sizeof({data}[0])}}'
# prefix of children
cpf = prefix+self.c_name
body_li = []
payload_li = []
for c in self._children:
if isinstance(c, File):
tp = 'ROMFS_DIRENT_FILE'
elif isinstance(c, Folder):
tp = 'ROMFS_DIRENT_DIR'
else:
assert False, 'Unkown instance:%s' % str(c)
body_li.append(body_fmt.format(type=tp,
name=c.name,
data=cpf+c.c_name))
payload_li.append(c.c_data(prefix=cpf))
# All the data we need is defined in payload so we should append the
# dirent to it. It also meet the depth-first policy in this code.
payload_li.append(dhead + ',\n'.join(body_li) + dtail)
return '\n\n'.join(payload_li)
@property
def entry_size(self):
return len(self._children)
def bin_data(self, base_addr=0x0):
'''Return StringIO object'''
# The binary layout is different from the C code layout. We put the
# dirent before the payload in this mode. But the idea is still simple:
# Depth-First.
#{
# rt_uint32_t type;
# const char *name;
# const rt_uint8_t *data;
# rt_size_t size;
#}
d_li = []
# payload base
p_base = base_addr + self.bin_fmt.size * self.entry_size
# the length to record how many data is in
v_len = p_base
# payload
p_li = []
for c in self._children:
if isinstance(c, File):
# ROMFS_DIRENT_FILE
tp = 0
elif isinstance(c, Folder):
# ROMFS_DIRENT_DIR
tp = 1
else: else:
mkromfs_output(('\t{ROMFS_DIRENT_DIR, "%s", RT_NULL, 0},\n' % fn)) assert False, 'Unkown instance:%s' % str(c)
for item in list: name = bytes(c.bin_name)
fullpath = os.path.join(path, item) name_addr = v_len
fn = fullpath[len(dirname):] v_len += len(name)
if fn[0] == sep:
fn = fn[1:] data = c.bin_data(base_addr=v_len)
fn = fn.replace('\\', '/') data_addr = v_len
# pad the data to 4 bytes boundary
subpath = fullpath[len(basename):] pad_len = 4
items = subpath.split(sep) if len(data) % pad_len != 0:
item_name = string.join(items, '_') data += '\0' * (pad_len - len(data) % pad_len)
item_name = item_name.replace('.', '_') v_len += len(data)
item_name = item_name.replace('-', '_')
subpath = subpath.replace('\\', '/') d_li.append(self.bin_fmt.pack(*self.bin_item(
if subpath[0] == '/': type=tp,
subpath = subpath[1:] name=name_addr,
data=data_addr,
if os.path.isfile(fullpath): size=c.entry_size)))
mkromfs_output(('\t{ROMFS_DIRENT_FILE, "%s", %s, sizeof(%s)},\n' % (fn, item_name, item_name)))
p_li.extend((name, data))
mkromfs_output('};\n\n')
return bytes().join(d_li) + bytes().join(p_li)
if __name__ == "__main__":
try: def get_c_data(tree):
basename = os.path.abspath(sys.argv[1]) # Handle the root dirent specially.
filename = os.path.abspath(sys.argv[2]) root_dirent_fmt = '''/* Generated by mkromfs. Edit with caution. */
except IndexError: #include <rtthread.h>
print "Usage: %s <dirname> <filename>" % sys.argv[0] #include <dfs_romfs.h>
raise SystemExit
{data}
output = file(filename, 'wt')
mkromfs_output("#include <dfs_romfs.h>\n\n") const struct romfs_dirent {name} = {{
mkromfs_dir(basename, is_root = True) ROMFS_DIRENT_DIR, "/", (rt_uint8_t *){rootdirent}, sizeof({rootdirent})/sizeof({rootdirent}[0])
}};
mkromfs_output("const struct romfs_dirent romfs_root = {ROMFS_DIRENT_DIR, \"/\", (rt_uint8_t*) _root_dirent, sizeof(_root_dirent)/sizeof(_root_dirent[0])};\n\n") '''
return root_dirent_fmt.format(name='romfs_root',
rootdirent=tree.c_name,
data=tree.c_data())
def get_bin_data(tree, base_addr):
v_len = base_addr + Folder.bin_fmt.size
name = bytes('/\0\0\0')
name_addr = v_len
v_len += len(name)
data_addr = v_len
# root entry
data = Folder.bin_fmt.pack(*Folder.bin_item(type=1,
name=name_addr,
data=data_addr,
size=tree.entry_size))
return data + name + tree.bin_data(v_len)
if __name__ == '__main__':
args = parser.parse_args()
os.chdir(args.rootdir)
tree = Folder('romfs_root')
tree.walk()
tree.sort()
if args.dump:
tree.dump()
if args.binary:
data = get_bin_data(tree, int(args.addr, 16))
else:
data = get_c_data(tree)
output = args.output
if not output:
output = sys.stdout
output.write(data)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册