Debian Codegraph @

travis/nasm-t.py

raw
1 #!/usr/bin/python3
2
3 import subprocess
4 import argparse
5 import difflib
6 import filecmp
7 import fnmatch
8 import json
9 import sys
10 import re
11 import os
12
13 fmtr_class = argparse.ArgumentDefaultsHelpFormatter
14 parser = argparse.ArgumentParser(prog = 'nasm-t.py',
15 formatter_class=fmtr_class)
16
17 parser.add_argument('-d', '--directory',
18 dest = 'dir', default = './travis/test',
19 help = 'Directory with tests')
20
21 parser.add_argument('--nasm',
22 dest = 'nasm', default = './nasm',
23 help = 'Nasm executable to use')
24
25 sp = parser.add_subparsers(dest = 'cmd')
26 for cmd in ['run']:
27 spp = sp.add_parser(cmd, help = 'Run test cases')
28 spp.add_argument('-t', '--test',
29 dest = 'test',
30 help = 'Run the selected test only',
31 required = False)
32 spp.add_argument('--stop',
33 dest = 'stop', default = 'y',
34 help = 'Stop immediately on failure (default "y")',
35 required = False)
36
37 for cmd in ['new']:
38 spp = sp.add_parser(cmd, help = 'Add a new test case')
39 spp.add_argument('--description',
40 dest = 'description', default = "Description of a test",
41 help = 'Description of a test',
42 required = False)
43 spp.add_argument('--id',
44 dest = 'id',
45 help = 'Test identifier/name',
46 required = True)
47 spp.add_argument('--format',
48 dest = 'format', default = 'bin',
49 help = 'Output format',
50 required = False)
51 spp.add_argument('--source',
52 dest = 'source',
53 help = 'Source file',
54 required = False)
55 spp.add_argument('--option',
56 dest = 'option',
57 default = '-Ox',
58 help = 'NASM options',
59 required = False)
60 spp.add_argument('--ref',
61 dest = 'ref',
62 help = 'Test reference',
63 required = False)
64 spp.add_argument('--error',
65 dest = 'error',
66 help = '"y" if test is supposed to fail or "i" to ignore',
67 required = False)
68 spp.add_argument('--output',
69 dest = 'output', default = 'y',
70 help = 'Output (compiled) file name (or "y")',
71 required = False)
72 spp.add_argument('--stdout',
73 dest = 'stdout', default = 'y',
74 help = 'Filename of stdout file (or "y")',
75 required = False)
76 spp.add_argument('--stderr',
77 dest = 'stderr', default = 'y',
78 help = 'Filename of stderr file (or "y")',
79 required = False)
80
81 for cmd in ['list']:
82 spp = sp.add_parser(cmd, help = 'List test cases')
83
84 for cmd in ['update']:
85 spp = sp.add_parser(cmd, help = 'Update test cases with new compiler')
86 spp.add_argument('-t', '--test',
87 dest = 'test',
88 help = 'Update the selected test only',
89 required = False)
90
91 map_fmt_ext = {
92 'bin': '.bin',
93 'elf': '.o',
94 'elf64': '.o',
95 'elf32': '.o',
96 'elfx32': '.o',
97 'ith': '.ith',
98 'srec': '.srec',
99 'obj': '.obj',
100 'win32': '.obj',
101 'win64': '.obj',
102 'coff': '.obj',
103 'macho': '.o',
104 'macho32': '.o',
105 'macho64': '.o',
106 'aout': '.out',
107 'aoutb': '.out',
108 'as86': '.o',
109 'rdf': '.rdf',
110 }
111
112 args = parser.parse_args()
113
114 if args.cmd == None:
115 parser.print_help()
116 sys.exit(64)
117
118 def read_stdfile(path):
119 with open(path, "rb") as f:
120 data = f.read().decode("utf-8","replace")
121 f.close()
122 return data
123
124 #
125 # Check if descriptor has mandatory fields
126 def is_valid_desc(desc):
127 if desc == None:
128 return False
129 if 'description' not in desc:
130 return False
131 if desc['description'] == "":
132 return False
133 return True
134
135 #
136 # Expand ref/id in descriptors array
137 def expand_templates(desc_array):
138 desc_ids = { }
139 for d in desc_array:
140 if 'id' in d:
141 desc_ids[d['id']] = d
142 for i, d in enumerate(desc_array):
143 if 'ref' in d and d['ref'] in desc_ids:
144 ref = desc_ids[d['ref']]
145 own = d.copy()
146 desc_array[i] = ref.copy()
147 for k, v in own.items():
148 desc_array[i][k] = v
149 del desc_array[i]['id']
150 return desc_array
151
152 def prepare_desc(desc, basedir, name, path):
153 if not is_valid_desc(desc):
154 return False
155 #
156 # Put private fields
157 desc['_base-dir'] = basedir
158 desc['_json-file'] = name
159 desc['_json-path'] = path
160 desc['_test-name'] = basedir + os.sep + name[:-5]
161 #
162 # If no target provided never update
163 if 'target' not in desc:
164 desc['target'] = []
165 desc['update'] = 'false'
166 #
167 # Which code to expect when nasm finishes
168 desc['_wait'] = 0
169 if 'error' in desc:
170 if desc['error'] == 'expected':
171 desc['_wait'] = 1
172 #
173 # Walk over targets and generate match templates
174 # if were not provided yet
175 for d in desc['target']:
176 if 'output' in d and not 'match' in d:
177 d['match'] = d['output'] + ".t"
178 return True
179
180 def read_json(path):
181 desc = None
182 try:
183 with open(path, "rb") as f:
184 try:
185 desc = json.loads(f.read().decode("utf-8","replace"))
186 except:
187 desc = None
188 finally:
189 f.close()
190 except:
191 pass
192 return desc
193
194 def read_desc(basedir, name):
195 path = basedir + os.sep + name
196 desc = read_json(path)
197 desc_array = []
198 if type(desc) == dict:
199 if prepare_desc(desc, basedir, name, path) == True:
200 desc_array += [desc]
201 elif type(desc) == list:
202 expand_templates(desc)
203 for de in desc:
204 if prepare_desc(de, basedir, name, path) == True:
205 desc_array += [de]
206 return desc_array
207
208 def collect_test_desc_from_file(path):
209 if not fnmatch.fnmatch(path, '*.json'):
210 path += '.json'
211 basedir = os.path.dirname(path)
212 filename = os.path.basename(path)
213 return read_desc(basedir, filename)
214
215 def collect_test_desc_from_dir(basedir):
216 desc_array = []
217 if os.path.isdir(basedir):
218 for filename in os.listdir(basedir):
219 if os.path.isdir(basedir + os.sep + filename):
220 desc_array += collect_test_desc_from_dir(basedir + os.sep + filename)
221 elif fnmatch.fnmatch(filename, '*.json'):
222 desc = read_desc(basedir, filename)
223 if desc == None:
224 continue
225 desc_array += desc
226 desc_array.sort(key=lambda x: x['_test-name'])
227 return desc_array
228
229 if args.cmd == 'list':
230 fmt_entry = '%-32s %s'
231 desc_array = collect_test_desc_from_dir(args.dir)
232 print(fmt_entry % ('Name', 'Description'))
233 for desc in desc_array:
234 print(fmt_entry % (desc['_test-name'], desc['description']))
235
236 def test_abort(test, message):
237 print("\t%s: %s" % (test, message))
238 print("=== Test %s ABORT ===" % (test))
239 sys.exit(2)
240 return False
241
242 def test_fail(test, message):
243 print("\t%s: %s" % (test, message))
244 print("=== Test %s FAIL ===" % (test))
245 return False
246
247 def test_skip(test, message):
248 print("\t%s: %s" % (test, message))
249 print("=== Test %s SKIP ===" % (test))
250 return True
251
252 def test_over(test):
253 print("=== Test %s ERROR OVER ===" % (test))
254 return True
255
256 def test_pass(test):
257 print("=== Test %s PASS ===" % (test))
258 return True
259
260 def test_updated(test):
261 print("=== Test %s UPDATED ===" % (test))
262 return True
263
264 def hexdump(path):
265 dump = ''
266 addr = 0
267 with open(path, 'rb') as f:
268 while b := f.read(16):
269 dump += "%08x " % (addr)
270 for i in range(16):
271 if (i == 8):
272 dump += " -"
273 if (i >= len(b)):
274 dump += " "
275 else:
276 dump += " %02x" % b[i]
277 dump += " |"
278 for i in range(16):
279 if (i >= len(b)):
280 c = ord(' ')
281 else:
282 c = b[i]
283 if (c < 32 or c > 126):
284 c = ord('.')
285 dump += chr(c)
286 dump += "|\n";
287 addr += 16
288 return dump
289
290 def show_std(stdname, data):
291 print("\t--- %s" % (stdname))
292 for i in data.split("\n"):
293 print("\t%s" % i)
294 print("\t---")
295
296 def cmp_std(from_name, from_data, match_name, match_data):
297 if from_data != match_data:
298 print("\t--- %s" % (from_name))
299 for i in from_data.split("\n"):
300 print("\t%s" % i)
301 print("\t--- %s" % (match_name))
302 for i in match_data.split("\n"):
303 print("\t%s" % i)
304
305 diff = difflib.unified_diff(from_data.split("\n"), match_data.split("\n"),
306 fromfile = from_name, tofile = match_name)
307 for i in diff:
308 print("\t%s" % i.strip("\n"))
309 print("\t---")
310 return False
311 return True
312
313 def show_diff(test, patha, pathb):
314 try:
315 sa = hexdump(patha)
316 sb = hexdump(pathb)
317 except OSError:
318 return test_fail(test, "Can't create dumps")
319
320 print("\t--- hexdump %s" % (patha))
321 for i in sa.split("\n"):
322 print("\t%s" % i)
323 print("\t--- hexdump %s" % (pathb))
324 for i in sb.split("\n"):
325 print("\t%s" % i)
326
327 diff = difflib.unified_diff(sa.split("\n"), sb.split("\n"),
328 fromfile = patha, tofile = pathb)
329 for i in diff:
330 print("\t%s" % i.strip("\n"))
331 print("\t---")
332 return True
333
334 def prepare_run_opts(desc):
335 opts = []
336
337 if 'format' in desc:
338 opts += ['-f', desc['format']]
339 if 'option' in desc:
340 opts += desc['option'].split(" ")
341 for t in desc['target']:
342 if 'output' in t:
343 if 'option' in t:
344 opts += t['option'].split(" ")
345 else:
346 opts += ['-o']
347 outfile = desc['_base-dir'] + os.sep + t['output']
348 opts += [outfile, '-L+', '-l', outfile + '.lst']
349 if 'stdout' in t or 'stderr' in t:
350 if 'option' in t:
351 opts += t['option'].split(" ")
352 if 'source' in desc:
353 opts += [desc['_base-dir'] + os.sep + desc['source']]
354 return opts
355
356 def exec_nasm(desc):
357 print("\tProcessing %s" % (desc['_test-name']))
358 opts = [args.nasm] + prepare_run_opts(desc)
359
360 nasm_env = os.environ.copy()
361 nasm_env['NASMENV'] = '--reproducible'
362
363 desc_env = desc.get('environ')
364 if desc_env:
365 for i in desc_env:
366 v = i.split('=')
367 if len(v) == 2:
368 nasm_env[v[0]] = v[1]
369 else:
370 nasm_env[v[0]] = None
371
372 print("\tExecuting %s" % (" ".join(opts)))
373 pnasm = subprocess.Popen(opts,
374 stdout = subprocess.PIPE,
375 stderr = subprocess.PIPE,
376 close_fds = True,
377 env = nasm_env)
378 if pnasm == None:
379 test_fail(desc['_test-name'], "Unable to execute test")
380 return None
381
382 #
383 # FIXME: For now 4M buffer is enough but
384 # better provide reading in a cycle.
385 stderr = pnasm.stderr.read(4194304).decode("utf-8","replace")
386 stdout = pnasm.stdout.read(4194304).decode("utf-8","replace")
387
388 pnasm.stdout.close()
389 pnasm.stderr.close()
390
391 wait_rc = pnasm.wait();
392
393 if desc['_wait'] != wait_rc:
394 if stdout != "":
395 show_std("stdout", stdout)
396 if stderr != "":
397 show_std("stderr", stderr)
398 test_fail(desc['_test-name'],
399 "Unexpected ret code: " + str(wait_rc))
400 return None, None, None
401 return pnasm, stdout, stderr
402
403 def test_run(desc):
404 print("=== Running %s ===" % (desc['_test-name']))
405
406 if 'disable' in desc:
407 return test_skip(desc['_test-name'], desc["disable"])
408
409 pnasm, stdout, stderr = exec_nasm(desc)
410 if pnasm == None:
411 return False
412
413 for t in desc['target']:
414 f = None
415 if 'filter' in t:
416 f = t['filter']
417 f_pat = re.compile(f['match'], re.M)
418 f_sub = f['subst']
419
420 if 'output' in t:
421 output = desc['_base-dir'] + os.sep + t['output']
422 match = desc['_base-dir'] + os.sep + t['match']
423 if desc['_wait'] == 1:
424 continue
425 print("\tComparing %s %s" % (output, match))
426 if filecmp.cmp(match, output) == False:
427 show_diff(desc['_test-name'], match, output)
428 return test_fail(desc['_test-name'], match + " and " + output + " files are different")
429 elif 'stdout' in t:
430 print("\tComparing stdout")
431 match = desc['_base-dir'] + os.sep + t['stdout']
432 match_data = read_stdfile(match)
433 if match_data == None:
434 return test_fail(test, "Can't read " + match)
435 out_data = stdout
436 if f:
437 out_data = f_pat.sub(f_sub, out_data, 0)
438 if cmp_std(match, match_data, 'stdout', out_data) == False:
439 return test_fail(desc['_test-name'], "Stdout mismatch")
440 else:
441 stdout = ""
442 elif 'stderr' in t:
443 print("\tComparing stderr")
444 match = desc['_base-dir'] + os.sep + t['stderr']
445 match_data = read_stdfile(match)
446 if match_data == None:
447 return test_fail(test, "Can't read " + match)
448 out_data = stderr
449 if f:
450 out_data = f_pat.sub(f_sub, out_data, 0)
451 if cmp_std(match, match_data, 'stderr', out_data) == False:
452 return test_fail(desc['_test-name'], "Stderr mismatch")
453 else:
454 stderr = ""
455
456 if stdout != "":
457 show_std("stdout", stdout)
458 return test_fail(desc['_test-name'], "Stdout is not empty")
459
460 if stderr != "":
461 show_std("stderr", stderr)
462 return test_fail(desc['_test-name'], "Stderr is not empty")
463
464 return test_pass(desc['_test-name'])
465
466 #
467 # Compile sources and generate new targets
468 def test_update(desc):
469 print("=== Updating %s ===" % (desc['_test-name']))
470
471 if 'update' in desc and desc['update'] == 'false':
472 return test_skip(desc['_test-name'], "No output provided")
473 if 'disable' in desc:
474 return test_skip(desc['_test-name'], desc["disable"])
475
476 pnasm, stdout, stderr = exec_nasm(desc)
477 if pnasm == None:
478 return False
479
480 for t in desc['target']:
481 if 'output' in t:
482 output = desc['_base-dir'] + os.sep + t['output']
483 match = desc['_base-dir'] + os.sep + t['match']
484 print("\tMoving %s to %s" % (output, match))
485 os.rename(output, match)
486 if 'stdout' in t:
487 match = desc['_base-dir'] + os.sep + t['stdout']
488 print("\tMoving %s to %s" % ('stdout', match))
489 with open(match, "wb") as f:
490 f.write(stdout.encode("utf-8"))
491 f.close()
492 if 'stderr' in t:
493 match = desc['_base-dir'] + os.sep + t['stderr']
494 print("\tMoving %s to %s" % ('stderr', match))
495 with open(match, "wb") as f:
496 f.write(stderr.encode("utf-8"))
497 f.close()
498
499 return test_updated(desc['_test-name'])
500
501 #
502 # Create a new empty test case
503 if args.cmd == 'new':
504 #
505 # If no source provided create one
506 # from (ID which is required)
507 if not args.source:
508 args.source = args.id + ".asm"
509
510 #
511 # Emulate "touch" on source file
512 path_asm = args.dir + os.sep + args.source
513 print("\tCreating %s" % (path_asm))
514 open(path_asm, 'a').close()
515
516 #
517 # Fill the test descriptor
518 #
519 # FIXME: We should probably use Jinja
520 path_json = args.dir + os.sep + args.id + ".json"
521 print("\tFilling descriptor %s" % (path_json))
522 with open(path_json, 'wb') as f:
523 f.write("[\n\t{\n".encode("utf-8"))
524 acc = []
525 if args.description:
526 acc.append("\t\t\"description\": \"{}\"".format(args.description))
527 acc.append("\t\t\"id\": \"{}\"".format(args.id))
528 if args.format:
529 acc.append("\t\t\"format\": \"{}\"".format(args.format))
530 acc.append("\t\t\"source\": \"{}\"".format(args.source))
531 if args.option:
532 acc.append("\t\t\"option\": \"{}\"".format(args.option))
533 if args.ref:
534 acc.append("\t\t\"ref\": \"{}\"".format(args.ref))
535 if args.error == 'y':
536 acc.append("\t\t\"error\": \"expected\"")
537 elif args.error == 'i':
538 acc.append("\t\t\"error\": \"over\"")
539 f.write(",\n".join(acc).encode("utf-8"))
540 if args.output or args.stdout or args.stderr:
541 acc = []
542 if args.output:
543 if args.output == 'y':
544 if args.format in map_fmt_ext:
545 args.output = args.id + map_fmt_ext[args.format]
546 acc.append("\t\t\t{{ \"output\": \"{}\" }}".format(args.output))
547 if args.stdout:
548 if args.stdout == 'y':
549 args.stdout = args.id + '.stdout'
550 acc.append("\t\t\t{{ \"stdout\": \"{}\" }}".format(args.stdout))
551 if args.stderr:
552 if args.stderr == 'y':
553 args.stderr = args.id + '.stderr'
554 acc.append("\t\t\t{{ \"stderr\": \"{}\" }}".format(args.stderr))
555 f.write(",\n".encode("utf-8"))
556 f.write("\t\t\"target\": [\n".encode("utf-8"))
557 f.write(",\n".join(acc).encode("utf-8"))
558 f.write("\n\t\t]".encode("utf-8"))
559 f.write("\n\t}\n]\n".encode("utf-8"))
560 f.close()
561
562 if args.cmd == 'run':
563 errors = 0
564 desc_array = []
565 if args.test == None:
566 desc_array = collect_test_desc_from_dir(args.dir)
567 else:
568 desc_array = collect_test_desc_from_file(args.test)
569 if len(desc_array) == 0:
570 test_abort(args.test, "Can't obtain test descriptors")
571
572 for desc in desc_array:
573 if test_run(desc) == False:
574 errors = 1;
575 if 'error' in desc and desc['error'] == 'over':
576 test_over(desc['_test-name'])
577 else:
578 errors = 1
579 if args.stop == 'y':
580 test_abort(desc['_test-name'], "Error detected")
581 sys.exit(errors)
582
583 if args.cmd == 'update':
584 desc_array = []
585 if args.test == None:
586 desc_array = collect_test_desc_from_dir(args.dir)
587 else:
588 desc_array = collect_test_desc_from_file(args.test)
589 if len(desc_array) == 0:
590 test_abort(args.test, "Can't obtain a test descriptors")
591
592 for desc in desc_array:
593 if test_update(desc) == False:
594 if 'error' in desc and desc['error'] == 'over':
595 test_over(desc['_test-name'])
596 else:
597 test_abort(desc['_test-name'], "Error detected")