Skip to content

Commit 371c556

Browse files
committed
feat(relinker): Optimize the syntax and format of python code
1 parent 92c8b68 commit 371c556

File tree

2 files changed

+259
-248
lines changed

2 files changed

+259
-248
lines changed

tools/cmake_utilities/scripts/relinker/configuration.py

Lines changed: 57 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
#!/usr/bin/env python3
22
#
3-
# SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
3+
# SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD
44
# SPDX-License-Identifier: Apache-2.0
55

6-
76
import argparse
87
import csv
98
import os
@@ -19,17 +18,18 @@
1918

2019
class sdkconfig_c:
2120
def __init__(self, path):
22-
lines = open(path).read().splitlines()
23-
config = dict()
21+
with open(path) as f:
22+
lines = f.read().splitlines()
23+
config = {}
2424
for l in lines:
2525
if len(l) > OPT_MIN_LEN and l[0] != '#':
26-
mo = re.match( r'(.*)=(.*)', l, re.M|re.I)
26+
mo = re.match(r'(.*)=(.*)', l, re.M | re.I)
2727
if mo:
28-
config[mo.group(1)]=mo.group(2).replace('"', '')
28+
config[mo.group(1)] = mo.group(2).replace('"', '')
2929
self.config = config
3030

31-
def index(self, i):
32-
return self.config[i]
31+
def index(self, key):
32+
return self.config[key]
3333

3434
def check(self, options):
3535
options = options.replace(' ', '')
@@ -57,33 +57,33 @@ class object_c:
5757
def read_dump_info(self, paths):
5858
new_env = os.environ.copy()
5959
new_env['LC_ALL'] = 'C'
60-
dumps = list()
60+
dumps = []
6161
print('paths:', paths)
6262
for path in paths:
6363
try:
64-
dump = StringIO(subprocess.check_output([espidf_objdump, '-t', path], env=new_env).decode())
65-
dumps.append(dump.readlines())
64+
dump_output = subprocess.check_output([espidf_objdump, '-t', path], env=new_env).decode()
65+
dumps.append(StringIO(dump_output).readlines())
6666
except subprocess.CalledProcessError as e:
67-
raise RuntimeError('cmd:%s result:%s'%(e.cmd, e.returncode))
67+
raise RuntimeError(f"Command '{e.cmd}' failed with exit code {e.returncode}")
6868
return dumps
6969

7070
def get_func_section(self, dumps, func):
7171
for dump in dumps:
72-
for l in dump:
73-
if ' %s'%(func) in l and '*UND*' not in l:
74-
m = re.match(r'(\S*)\s*([glw])\s*([F|O])\s*(\S*)\s*(\S*)\s*(\S*)\s*', l, re.M|re.I)
72+
for line in dump:
73+
if f' {func}' in line and '*UND*' not in line:
74+
m = re.match(r'(\S*)\s*([glw])\s*([F|O])\s*(\S*)\s*(\S*)\s*(\S*)\s*', line, re.M | re.I)
7575
if m and m[6] == func:
76-
return m[4].replace('.text.', '')
76+
return m.group(4).replace('.text.', '')
7777
if espidf_missing_function_info:
78-
print('%s failed to find section'%(func))
78+
print(f'{func} failed to find section')
7979
return None
8080
else:
81-
raise RuntimeError('%s failed to find section'%(func))
81+
raise RuntimeError(f'{func} failed to find section')
8282

8383
def __init__(self, name, paths, library):
8484
self.name = name
8585
self.library = library
86-
self.funcs = dict()
86+
self.funcs = {}
8787
self.paths = paths
8888
self.dumps = self.read_dump_info(paths)
8989
self.section_all = False
@@ -106,17 +106,17 @@ def append(self, func):
106106
else:
107107
section = self.get_func_section(self.dumps, func)
108108

109-
if section != None:
109+
if section is not None:
110110
self.funcs[func] = section
111111

112112
def functions(self):
113-
nlist = list()
113+
nlist = []
114114
for i in self.funcs:
115115
nlist.append(i)
116116
return nlist
117117

118118
def sections(self):
119-
nlist = list()
119+
nlist = []
120120
for i in self.funcs:
121121
nlist.append(self.funcs[i])
122122
return nlist
@@ -125,7 +125,7 @@ class library_c:
125125
def __init__(self, name, path):
126126
self.name = name
127127
self.path = path
128-
self.objs = dict()
128+
self.objs = {}
129129

130130
def append(self, obj, path, func):
131131
if obj not in self.objs:
@@ -134,7 +134,7 @@ def append(self, obj, path, func):
134134

135135
class libraries_c:
136136
def __init__(self):
137-
self.libs = dict()
137+
self.libs = {}
138138

139139
def append(self, lib, lib_path, obj, obj_path, func):
140140
if lib not in self.libs:
@@ -146,28 +146,28 @@ def dump(self):
146146
lib = self.libs[libname]
147147
for objname in lib.objs:
148148
obj = lib.objs[objname]
149-
print('%s, %s, %s, %s'%(libname, objname, obj.path, obj.funcs))
149+
print(f'{libname}, {objname}, {obj.path}, {obj.funcs}')
150150

151151
class paths_c:
152152
def __init__(self):
153-
self.paths = dict()
153+
self.paths = {}
154154

155155
def append(self, lib, obj, path):
156156
if '$IDF_PATH' in path:
157157
path = path.replace('$IDF_PATH', os.environ['IDF_PATH'])
158158

159159
if lib not in self.paths:
160-
self.paths[lib] = dict()
160+
self.paths[lib] = {}
161161
if obj not in self.paths[lib]:
162-
self.paths[lib][obj] = list()
162+
self.paths[lib][obj] = []
163163
self.paths[lib][obj].append(path)
164164

165165
def index(self, lib, obj):
166166
if lib not in self.paths:
167167
return None
168168
if '*' in self.paths[lib]:
169169
obj = '*'
170-
return self.paths[lib][obj]
170+
return self.paths[lib].get(obj)
171171

172172
def generator(library_file, object_file, function_file, sdkconfig_file, missing_function_info, objdump='riscv32-esp-elf-objdump'):
173173
global espidf_objdump, espidf_missing_function_info
@@ -177,23 +177,29 @@ def generator(library_file, object_file, function_file, sdkconfig_file, missing_
177177
sdkconfig = sdkconfig_c(sdkconfig_file)
178178

179179
lib_paths = paths_c()
180-
for p in csv.DictReader(open(library_file, 'r')):
181-
lib_paths.append(p['library'], '*', p['path'])
180+
with open(library_file, newline='') as csvfile:
181+
reader = csv.DictReader(csvfile)
182+
for row in reader:
183+
lib_paths.append(row['library'], '*', row['path'])
182184

183185
obj_paths = paths_c()
184-
for p in csv.DictReader(open(object_file, 'r')):
185-
obj_paths.append(p['library'], p['object'], p['path'])
186+
with open(object_file, newline='') as csvfile:
187+
reader = csv.DictReader(csvfile)
188+
for row in reader:
189+
obj_paths.append(row['library'], row['object'], row['path'])
186190

187191
libraries = libraries_c()
188-
for d in csv.DictReader(open(function_file, 'r')):
189-
if d['option'] and sdkconfig.check(d['option']) == False:
190-
print('skip %s(%s)'%(d['function'], d['option']))
191-
continue
192-
lib_path = lib_paths.index(d['library'], '*')
193-
obj_path = obj_paths.index(d['library'], d['object'])
194-
if not obj_path:
195-
obj_path = lib_path
196-
libraries.append(d['library'], lib_path[0], d['object'], obj_path, d['function'])
192+
with open(function_file, newline='') as csvfile:
193+
reader = csv.DictReader(csvfile)
194+
for row in reader:
195+
if row['option'] and not sdkconfig.check(row['option']):
196+
print(f'skip {row["function"]}({row["option"]})')
197+
continue
198+
lib_path = lib_paths.index(row['library'], '*')
199+
obj_path = obj_paths.index(row['library'], row['object'])
200+
if not obj_path:
201+
obj_path = lib_path
202+
libraries.append(row['library'], lib_path[0], row['object'], obj_path, row['function'])
197203
return libraries
198204

199205
def main():
@@ -202,26 +208,30 @@ def main():
202208
argparser.add_argument(
203209
'--library', '-l',
204210
help='Library description file',
205-
type=str)
211+
type=str,
212+
required=True)
206213

207214
argparser.add_argument(
208215
'--object', '-b',
209216
help='Object description file',
210-
type=str)
217+
type=str,
218+
required=True)
211219

212220
argparser.add_argument(
213221
'--function', '-f',
214222
help='Function description file',
215-
type=str)
223+
type=str,
224+
required=True)
216225

217226
argparser.add_argument(
218227
'--sdkconfig', '-s',
219228
help='sdkconfig file',
220-
type=str)
229+
type=str,
230+
required=True)
221231

222232
args = argparser.parse_args()
223233

224-
libraries = generator(args.library, args.object, args.function, args.sdkconfig)
234+
libraries = generator(args.library, args.object, args.function, args.sdkconfig, espidf_missing_function_info)
225235
# libraries.dump()
226236

227237
if __name__ == '__main__':

0 commit comments

Comments
 (0)