mirror of
https://github.com/anrieff/libcpuid
synced 2025-06-07 00:51:40 +00:00
Use f-strings in Python scripts
This commit is contained in:
parent
c818294b89
commit
aeb788c723
3 changed files with 30 additions and 30 deletions
|
@ -9,7 +9,7 @@ git_root_dir = os.popen("git rev-parse --show-toplevel").read().splitlines()
|
||||||
|
|
||||||
err = 0
|
err = 0
|
||||||
def getEnumElements(enumName):
|
def getEnumElements(enumName):
|
||||||
f = open("%s/libcpuid.h" % args.root_dir, "r")
|
f = open(f"{args.root_dir}/libcpuid.h", "r")
|
||||||
l = []
|
l = []
|
||||||
on = False
|
on = False
|
||||||
rexp = re.compile(r'^\s*([A-Z0-9_]+)(\s*=\s*[A-Z0-9_]+)?\s*,.*$')
|
rexp = re.compile(r'^\s*([A-Z0-9_]+)(\s*=\s*[A-Z0-9_]+)?\s*,.*$')
|
||||||
|
@ -28,7 +28,7 @@ def getEnumElements(enumName):
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def getConstant(constantName):
|
def getConstant(constantName):
|
||||||
f = open("%s/libcpuid_constants.h" % args.root_dir, "r")
|
f = open(f"{args.root_dir}/libcpuid_constants.h", "r")
|
||||||
value = 0
|
value = 0
|
||||||
for line in f:
|
for line in f:
|
||||||
items = line.strip().split()
|
items = line.strip().split()
|
||||||
|
@ -38,10 +38,10 @@ def getConstant(constantName):
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def checkEnumSize(enumName, constantName):
|
def checkEnumSize(enumName, constantName):
|
||||||
print("Checking enum `%s':" % enumName, end=' ')
|
print(f"Checking enum `{enumName}':", end=' ')
|
||||||
count = len(getEnumElements(enumName)) - 1
|
count = len(getEnumElements(enumName)) - 1
|
||||||
themax = getConstant(constantName)
|
themax = getConstant(constantName)
|
||||||
print("%d elements; max size (%s=%d)..." % (count, constantName, themax), end=' ')
|
print(f"{count} elements; max size ({constantName}={themax})...", end=' ')
|
||||||
if count > themax:
|
if count > themax:
|
||||||
err += 1
|
err += 1
|
||||||
print("FAILED")
|
print("FAILED")
|
||||||
|
@ -70,7 +70,7 @@ checkEnumSize("cpu_sgx_feature_t", "SGX_FLAGS_MAX")
|
||||||
|
|
||||||
rexp = re.compile('.*{ CPU_FEATURE_([^,]+), "([^"]+)".*}.*')
|
rexp = re.compile('.*{ CPU_FEATURE_([^,]+), "([^"]+)".*}.*')
|
||||||
print("Finding features:")
|
print("Finding features:")
|
||||||
for fn in glob.glob("%s/*.c" % args.root_dir):
|
for fn in glob.glob(f"{args.root_dir}/*.c"):
|
||||||
f = open(fn, "rt")
|
f = open(fn, "rt")
|
||||||
line = 1
|
line = 1
|
||||||
nfeat = 0
|
nfeat = 0
|
||||||
|
@ -81,16 +81,16 @@ for fn in glob.glob("%s/*.c" % args.root_dir):
|
||||||
assert len(res) == 1, "Too many matches"
|
assert len(res) == 1, "Too many matches"
|
||||||
if res[0][0].lower() != res[0][1]:
|
if res[0][0].lower() != res[0][1]:
|
||||||
err += 1
|
err += 1
|
||||||
print("..Mismatch - %s:%d - `%s' vs `%s'" % (os.path.basename(fn), line, res[0][0], res[0][1]))
|
print(f"..Mismatch - {os.path.basename(fn)}:{line} - `{res[0][0]}' vs `{res[0][1]}'")
|
||||||
line += 1
|
line += 1
|
||||||
if nfeat:
|
if nfeat:
|
||||||
print(" %s: %d features described" % (os.path.basename(fn), nfeat))
|
print(f" {os.path.basename(fn)}: {nfeat} features described")
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
# Check whether all features are converted by cpu_feature_str():
|
# Check whether all features are converted by cpu_feature_str():
|
||||||
|
|
||||||
allf = []
|
allf = []
|
||||||
f = open("%s/libcpuid.h" % args.root_dir, "rt")
|
f = open(f"{args.root_dir}/libcpuid.h", "rt")
|
||||||
rexp = re.compile('\t(CPU_FEATURE_[^, ]+).*')
|
rexp = re.compile('\t(CPU_FEATURE_[^, ]+).*')
|
||||||
for s in f.readlines():
|
for s in f.readlines():
|
||||||
if rexp.match(s):
|
if rexp.match(s):
|
||||||
|
@ -100,22 +100,22 @@ f.close()
|
||||||
|
|
||||||
impf = []
|
impf = []
|
||||||
rexp = re.compile('\t+{ (CPU_FEATURE_[^,]+).*')
|
rexp = re.compile('\t+{ (CPU_FEATURE_[^,]+).*')
|
||||||
f = open("%s/cpuid_main.c" % args.root_dir, "rt")
|
f = open(f"{args.root_dir}/cpuid_main.c", "rt")
|
||||||
for s in f.readlines():
|
for s in f.readlines():
|
||||||
if rexp.match(s):
|
if rexp.match(s):
|
||||||
entry = rexp.findall(s)[0]
|
entry = rexp.findall(s)[0]
|
||||||
if entry in impf:
|
if entry in impf:
|
||||||
err += 1
|
err += 1
|
||||||
print("cpu_feature_str(): duplicate entry: %s" % entry)
|
print(f"cpu_feature_str(): duplicate entry: {entry}")
|
||||||
impf.append(entry)
|
impf.append(entry)
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
print("Found %d total features and %d named features" % (len(allf), len(impf)))
|
print(f"Found {len(allf)} total features and {len(impf)} named features")
|
||||||
|
|
||||||
for feature in allf:
|
for feature in allf:
|
||||||
if not feature in impf:
|
if not feature in impf:
|
||||||
err += 1
|
err += 1
|
||||||
print("cpu_feature_str(): don't have entry for %s" % feature)
|
print(f"cpu_feature_str(): don't have entry for {feature}")
|
||||||
|
|
||||||
# Check whether all features have detection code:
|
# Check whether all features have detection code:
|
||||||
print("Checking whether all features have detection code...", end=' ')
|
print("Checking whether all features have detection code...", end=' ')
|
||||||
|
@ -127,7 +127,7 @@ rexp1 = re.compile(r'.*\[(CPU_FEATURE_[^ \]]+)\]\s*=\s*{.*') # e.g. "[CPU_FEATUR
|
||||||
rexp2 = re.compile(r'.*(CPU_FEATURE_[^ ,]+),\s*FEATURE_LEVEL_ARM_.*') # e.g. "set_feature_status(data, ext_status, (mte_frac == 0b0000), CPU_FEATURE_MTE_ASYNC, FEATURE_LEVEL_ARM_V8_5_A, -1);"
|
rexp2 = re.compile(r'.*(CPU_FEATURE_[^ ,]+),\s*FEATURE_LEVEL_ARM_.*') # e.g. "set_feature_status(data, ext_status, (mte_frac == 0b0000), CPU_FEATURE_MTE_ASYNC, FEATURE_LEVEL_ARM_V8_5_A, -1);"
|
||||||
rexp3 = re.compile(r'.*(CPU_FEATURE_[^ }]+).*') # e.g. "{ 28, CPU_FEATURE_HT },"
|
rexp3 = re.compile(r'.*(CPU_FEATURE_[^ }]+).*') # e.g. "{ 28, CPU_FEATURE_HT },"
|
||||||
|
|
||||||
for fn in glob.glob("%s/*.c" % args.root_dir):
|
for fn in glob.glob(f"{args.root_dir}/*.c"):
|
||||||
f = open(fn, "rt")
|
f = open(fn, "rt")
|
||||||
files_code[fn] = []
|
files_code[fn] = []
|
||||||
for s in f.readlines():
|
for s in f.readlines():
|
||||||
|
@ -157,13 +157,13 @@ for feature in allf:
|
||||||
print("FAILED:")
|
print("FAILED:")
|
||||||
firstError = False
|
firstError = False
|
||||||
err += 1
|
err += 1
|
||||||
print("..No detection code for %s" % feature)
|
print(f"..No detection code for {feature}")
|
||||||
if len(matching_files) > 1 and feature not in features_whitelist:
|
if len(matching_files) > 1 and feature not in features_whitelist:
|
||||||
if firstError:
|
if firstError:
|
||||||
print("FAILED:")
|
print("FAILED:")
|
||||||
firstError = False
|
firstError = False
|
||||||
err += 1
|
err += 1
|
||||||
print("..Conflicting detection code for %s in files %s" % (feature, " and ".join(matching_files)))
|
print(f"..Conflicting detection code for {feature} in files {' and '.join(matching_files)}")
|
||||||
|
|
||||||
if firstError:
|
if firstError:
|
||||||
print("All OK.")
|
print("All OK.")
|
||||||
|
@ -178,7 +178,7 @@ definitions = 0
|
||||||
match_entry_fields = 11 # this number needs to change if the definition of match_entry_t ever changes
|
match_entry_fields = 11 # this number needs to change if the definition of match_entry_t ever changes
|
||||||
codename_str_max = 64-1 # this number needs to change if the value of CODENAME_STR_MAX ever changes
|
codename_str_max = 64-1 # this number needs to change if the value of CODENAME_STR_MAX ever changes
|
||||||
common_cache_sizes = ["8", "16", "32", "64", "128", "256", "512", "1024", "2048", "3072", "4096", "6144", "8192", "12288", "16384"]
|
common_cache_sizes = ["8", "16", "32", "64", "128", "256", "512", "1024", "2048", "3072", "4096", "6144", "8192", "12288", "16384"]
|
||||||
for fn in glob.glob("%s/*.c" % args.root_dir):
|
for fn in glob.glob(f"{args.root_dir}/*.c"):
|
||||||
bfn = os.path.basename(fn)
|
bfn = os.path.basename(fn)
|
||||||
nline = 0
|
nline = 0
|
||||||
f = open(fn, "rt")
|
f = open(fn, "rt")
|
||||||
|
@ -202,23 +202,23 @@ for fn in glob.glob("%s/*.c" % args.root_dir):
|
||||||
s = parts[match_entry_fields-1].strip()
|
s = parts[match_entry_fields-1].strip()
|
||||||
if s[0] != '"' or s[-1] != '"':
|
if s[0] != '"' or s[-1] != '"':
|
||||||
err += 1
|
err += 1
|
||||||
print("..Warning, %s:%d - cannot correctly handle the cpu codename" % (bfn, nline))
|
print(f"..Warning, {bfn}:{nline} - cannot correctly handle the cpu codename")
|
||||||
allok = False
|
allok = False
|
||||||
continue
|
continue
|
||||||
s = s[1:-1]
|
s = s[1:-1]
|
||||||
if len(s) > codename_str_max:
|
if len(s) > codename_str_max:
|
||||||
err += 1
|
err += 1
|
||||||
print("..%s:%d - codename (%s) is longer than %d characters!" % (bfn, nline, s, codename_str_max))
|
print(f"..{bfn}:{nline} - codename ({s}) is longer than {codename_str_max} characters!")
|
||||||
allok = False
|
allok = False
|
||||||
if cache_exp.match(s):
|
if cache_exp.match(s):
|
||||||
cache_size = cache_exp.findall(s)[0][1:-1]
|
cache_size = cache_exp.findall(s)[0][1:-1]
|
||||||
if not cache_size in common_cache_sizes:
|
if not cache_size in common_cache_sizes:
|
||||||
err += 1
|
err += 1
|
||||||
print("..Warning, %s:%d - suspicious cache size in codename [%s] (%s)" % (bfn, nline, s, cache_size))
|
print(f"..Warning, {bfn}:{nline} - suspicious cache size in codename [{s}] ({cache_size})")
|
||||||
allok = False
|
allok = False
|
||||||
if cdefs:
|
if cdefs:
|
||||||
definitions += 1
|
definitions += 1
|
||||||
print(" %s: %d processor definitions," % (bfn, cdefs), end=' ')
|
print(f" {bfn}: {cdefs} processor definitions,", end=' ')
|
||||||
if allok:
|
if allok:
|
||||||
print("all OK")
|
print("all OK")
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -49,7 +49,7 @@ def readResultFile():
|
||||||
if field in numeric:
|
if field in numeric:
|
||||||
value = s[s.find(":")+1:].strip()
|
value = s[s.find(":")+1:].strip()
|
||||||
if not rexp.match(value):
|
if not rexp.match(value):
|
||||||
raise "Bad format of value: [%s]" % s
|
raise f"Bad format of value: [{s}]"
|
||||||
repdata.append(rexp.findall(value)[0])
|
repdata.append(rexp.findall(value)[0])
|
||||||
if "CPU Info for type" in field:
|
if "CPU Info for type" in field:
|
||||||
repdata.append(delimiter)
|
repdata.append(delimiter)
|
||||||
|
|
|
@ -34,8 +34,8 @@ def make_tempname(prefix):
|
||||||
return prefix
|
return prefix
|
||||||
|
|
||||||
def fmt_error(err):
|
def fmt_error(err):
|
||||||
pfix = " %s: " % err[0]
|
pfix = f" {err[0]}: "
|
||||||
return "%sexpected `%s'\n%sgot `%s'" % (pfix, err[1], " "*len(pfix), err[2])
|
return "{} expected `{}'\n{} got `{}'".format(pfix, err[1], ' '*len(pfix), err[2])
|
||||||
|
|
||||||
def fixFile(filename, input_lines, output_lines):
|
def fixFile(filename, input_lines, output_lines):
|
||||||
f = open(filename, "wt")
|
f = open(filename, "wt")
|
||||||
|
@ -50,14 +50,14 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
|
||||||
f = open(fninp, "wt")
|
f = open(fninp, "wt")
|
||||||
f.writelines([s + "\n" for s in inp])
|
f.writelines([s + "\n" for s in inp])
|
||||||
f.close()
|
f.close()
|
||||||
architecture = os.popen("%s --load=%s --architecture" % (binary, fninp)).read().splitlines()[-1]
|
architecture = os.popen(f"{binary} --load={fninp} --architecture").read().splitlines()[-1]
|
||||||
if architecture == "x86":
|
if architecture == "x86":
|
||||||
fields = fields_x86
|
fields = fields_x86
|
||||||
elif architecture == "ARM":
|
elif architecture == "ARM":
|
||||||
fields = fields_arm
|
fields = fields_arm
|
||||||
else:
|
else:
|
||||||
fields = []
|
fields = []
|
||||||
cmd = "%s --load=%s --outfile=%s %s" % (binary, fninp, fnoutp, " ".join(["--" + s for s in fields]))
|
cmd = f"{binary} --load={fninp} --outfile={fnoutp} {' '.join(['--' + s for s in fields])}"
|
||||||
os.system(cmd)
|
os.system(cmd)
|
||||||
os.unlink(fninp)
|
os.unlink(fninp)
|
||||||
real_out = []
|
real_out = []
|
||||||
|
@ -77,7 +77,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
|
||||||
fixFile(test_file_name, inp, real_out_delim)
|
fixFile(test_file_name, inp, real_out_delim)
|
||||||
return "Number of records, fixed."
|
return "Number of records, fixed."
|
||||||
else:
|
else:
|
||||||
return "Unexpected number of records returned\n - expected length %d\n - real length %d\n - %d fields" % (len(expected_out), len(real_out), len(fields) * num_cpu_type)
|
return "Unexpected number of records returned\n - expected length {}\n - real length {}\n - {} fields".format(len(expected_out), len(real_out), len(fields) * num_cpu_type)
|
||||||
err_fields = []
|
err_fields = []
|
||||||
for i in range(len(real_out)):
|
for i in range(len(real_out)):
|
||||||
if real_out[i] != expected_out[i]:
|
if real_out[i] != expected_out[i]:
|
||||||
|
@ -89,7 +89,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
|
||||||
fixFile(test_file_name, inp, real_out_delim)
|
fixFile(test_file_name, inp, real_out_delim)
|
||||||
return "Mismatch, fixed."
|
return "Mismatch, fixed."
|
||||||
else:
|
else:
|
||||||
return "Mismatch in fields:\n%s" % "\n".join([fmt_error(err) for err in err_fields])
|
return "Mismatch in fields:\n{}".format('\n'.join([fmt_error(err) for err in err_fields]))
|
||||||
|
|
||||||
def is_regular_file(filename):
|
def is_regular_file(filename):
|
||||||
try:
|
try:
|
||||||
|
@ -142,7 +142,7 @@ filelist = []
|
||||||
for input_test_file in args.input_test_files:
|
for input_test_file in args.input_test_files:
|
||||||
if Path(input_test_file).is_dir():
|
if Path(input_test_file).is_dir():
|
||||||
# gather all *.test files from subdirs amd, intel and cie:
|
# gather all *.test files from subdirs amd, intel and cie:
|
||||||
for dirpath, dirnames, filenames in Path(input_test_file).walk():
|
for dirpath, dirnames, filenames in os.walk(input_test_file):
|
||||||
filelist += [PurePath(dirpath).joinpath(fn) for fn in filenames if Path(fn).suffixes[0] == ".test"]
|
filelist += [PurePath(dirpath).joinpath(fn) for fn in filenames if Path(fn).suffixes[0] == ".test"]
|
||||||
else:
|
else:
|
||||||
filelist.append(input_test_file)
|
filelist.append(input_test_file)
|
||||||
|
@ -161,7 +161,7 @@ for test_file_name_raw in filelist:
|
||||||
if test_file_name.suffixes[1] == ".xz":
|
if test_file_name.suffixes[1] == ".xz":
|
||||||
f = lzma.open(test_file_name, "rt")
|
f = lzma.open(test_file_name, "rt")
|
||||||
else:
|
else:
|
||||||
print("Test [%s]: skipped because %s is not supported" % (test_file_name.name, "".join(test_file_name.suffixes[1:])))
|
print(f"Test [{test_file_name.name}]: skipped because {''.join(test_file_name.suffixes[1:])} is not supported")
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
# Plain text file
|
# Plain text file
|
||||||
|
@ -180,7 +180,7 @@ for test_file_name_raw in filelist:
|
||||||
f.close()
|
f.close()
|
||||||
#codename = current_output[len(current_output) - 2]
|
#codename = current_output[len(current_output) - 2]
|
||||||
result = do_test(current_input, current_output, args.cpuid_tool, test_file_name, num_cpu_type)
|
result = do_test(current_input, current_output, args.cpuid_tool, test_file_name, num_cpu_type)
|
||||||
print("Test [%s]: %s" % (test_file_name.name, result))
|
print(f"Test [{test_file_name.name}]: {result}")
|
||||||
if result != "OK":
|
if result != "OK":
|
||||||
errors = True
|
errors = True
|
||||||
build_output = False
|
build_output = False
|
||||||
|
|
Loading…
Add table
Reference in a new issue