2 # SymbiYosys (sby) -- Front-end for Yosys-based formal verification flows
4 # Copyright (C) 2016 Claire Xenia Wolf <claire@yosyshq.com>
6 # Permission to use, copy, modify, and/or distribute this software for any
7 # purpose with or without fee is hereby granted, provided that the above
8 # copyright notice and this permission notice appear in all copies.
10 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 import os
, re
, sys
, signal
, platform
20 if os
.name
== "posix":
21 import resource
, fcntl
23 from shutil
import copyfile
, copytree
, rmtree
24 from select
import select
25 from time
import time
, localtime
, sleep
, strftime
26 from sby_design
import SbyProperty
, SbyModule
, design_hierarchy
28 all_procs_running
= []
30 def force_shutdown(signum
, frame
):
31 print("SBY ---- Keyboard interrupt or external termination signal ----", flush
=True)
32 for proc
in list(all_procs_running
):
36 if os
.name
== "posix":
37 signal
.signal(signal
.SIGHUP
, force_shutdown
)
38 signal
.signal(signal
.SIGINT
, force_shutdown
)
39 signal
.signal(signal
.SIGTERM
, force_shutdown
)
41 def process_filename(filename
):
42 if filename
.startswith("~/"):
43 filename
= os
.environ
['HOME'] + filename
[1:]
45 filename
= os
.path
.expandvars(filename
)
50 def __init__(self
, task
, info
, deps
, cmdline
, logfile
=None, logstderr
=True, silent
=False):
53 self
.terminated
= False
54 self
.checkretcode
= False
58 if os
.name
== "posix":
59 self
.cmdline
= cmdline
61 # Windows command interpreter equivalents for sequential
62 # commands (; => &) command grouping ({} => ()).
68 parts
= cmdline
.split("'")
69 for i
in range(len(parts
)):
71 cmdline_copy
= parts
[i
]
72 for u
, w
in replacements
.items():
73 cmdline_copy
= cmdline_copy
.replace(u
, w
)
74 parts
[i
] = cmdline_copy
75 self
.cmdline
= '"'.join(parts
)
76 self
.logfile
= logfile
77 self
.noprintregex
= None
80 self
.logstderr
= logstderr
83 self
.task
.procs_pending
.append(self
)
86 dep
.register_dep(self
)
88 self
.output_callback
= None
89 self
.exit_callback
= None
90 self
.error_callback
= None
92 def register_dep(self
, next_proc
):
96 self
.notify
.append(next_proc
)
99 if line
is not None and (self
.noprintregex
is None or not self
.noprintregex
.match(line
)):
100 if self
.logfile
is not None:
101 print(line
, file=self
.logfile
)
102 self
.task
.log(f
"{self.info}: {line}")
104 def handle_output(self
, line
):
105 if self
.terminated
or len(line
) == 0:
107 if self
.output_callback
is not None:
108 line
= self
.output_callback(line
)
111 def handle_exit(self
, retcode
):
114 if self
.logfile
is not None:
116 if self
.exit_callback
is not None:
117 self
.exit_callback(retcode
)
119 def handle_error(self
, retcode
):
122 if self
.logfile
is not None:
124 if self
.error_callback
is not None:
125 self
.error_callback(retcode
)
127 def terminate(self
, timeout
=False):
128 if self
.task
.opt_wait
and not timeout
:
132 self
.task
.log(f
"{self.info}: terminating process")
133 if os
.name
== "posix":
135 os
.killpg(self
.p
.pid
, signal
.SIGTERM
)
136 except PermissionError
:
139 self
.task
.procs_running
.remove(self
)
140 all_procs_running
.remove(self
)
141 self
.terminated
= True
144 if self
.finished
or self
.terminated
:
148 for dep
in self
.deps
:
153 self
.task
.log(f
"{self.info}: starting process \"{self.cmdline}\"")
155 if os
.name
== "posix":
157 signal
.signal(signal
.SIGINT
, signal
.SIG_IGN
)
160 self
.p
= subprocess
.Popen(["/usr/bin/env", "bash", "-c", self
.cmdline
], stdin
=subprocess
.DEVNULL
, stdout
=subprocess
.PIPE
,
161 stderr
=(subprocess
.STDOUT
if self
.logstderr
else None), preexec_fn
=preexec_fn
)
163 fl
= fcntl
.fcntl(self
.p
.stdout
, fcntl
.F_GETFL
)
164 fcntl
.fcntl(self
.p
.stdout
, fcntl
.F_SETFL
, fl | os
.O_NONBLOCK
)
167 self
.p
= subprocess
.Popen(self
.cmdline
, shell
=True, stdin
=subprocess
.DEVNULL
, stdout
=subprocess
.PIPE
,
168 stderr
=(subprocess
.STDOUT
if self
.logstderr
else None))
170 self
.task
.procs_pending
.remove(self
)
171 self
.task
.procs_running
.append(self
)
172 all_procs_running
.append(self
)
177 outs
= self
.p
.stdout
.readline().decode("utf-8")
178 if len(outs
) == 0: break
180 self
.linebuffer
+= outs
182 outs
= (self
.linebuffer
+ outs
).strip()
184 self
.handle_output(outs
)
186 if self
.p
.poll() is not None:
188 self
.task
.log(f
"{self.info}: finished (returncode={self.p.returncode})")
189 self
.task
.procs_running
.remove(self
)
190 all_procs_running
.remove(self
)
193 if self
.p
.returncode
== 127:
194 self
.task
.status
= "ERROR"
196 self
.task
.log(f
"{self.info}: COMMAND NOT FOUND. ERROR.")
197 self
.handle_error(self
.p
.returncode
)
198 self
.terminated
= True
199 self
.task
.terminate()
202 if self
.checkretcode
and self
.p
.returncode
!= 0:
203 self
.task
.status
= "ERROR"
205 self
.task
.log(f
"{self.info}: task failed. ERROR.")
206 self
.handle_error(self
.p
.returncode
)
207 self
.terminated
= True
208 self
.task
.terminate()
211 self
.handle_exit(self
.p
.returncode
)
214 for next_proc
in self
.notify
:
219 class SbyAbort(BaseException
):
225 self
.options
= dict()
226 self
.engines
= list()
229 self
.verbatim_files
= dict()
232 def parse_config(self
, f
):
237 if mode
in ["options", "engines", "files"]:
238 line
= re
.sub(r
"\s*(\s#.*)?$", "", line
)
239 if line
== "" or line
[0] == "#":
244 if mode
is None and (len(line
) == 0 or line
[0] == "#"):
246 match
= re
.match(r
"^\s*\[(.*)\]\s*$", line
)
248 entries
= match
.group(1).split()
249 if len(entries
) == 0:
250 self
.error(f
"sby file syntax error: {line}")
252 if entries
[0] == "options":
254 if len(self
.options
) != 0 or len(entries
) != 1:
255 self
.error(f
"sby file syntax error: {line}")
258 if entries
[0] == "engines":
260 if len(self
.engines
) != 0 or len(entries
) != 1:
261 self
.error(f
"sby file syntax error: {line}")
264 if entries
[0] == "script":
266 if len(self
.script
) != 0 or len(entries
) != 1:
267 self
.error(f
"sby file syntax error: {line}")
270 if entries
[0] == "file":
272 if len(entries
) != 2:
273 self
.error(f
"sby file syntax error: {line}")
274 current_verbatim_file
= entries
[1]
275 if current_verbatim_file
in self
.verbatim_files
:
276 self
.error(f
"duplicate file: {entries[1]}")
277 self
.verbatim_files
[current_verbatim_file
] = list()
280 if entries
[0] == "files":
282 if len(entries
) != 1:
283 self
.error(f
"sby file syntax error: {line}")
286 self
.error(f
"sby file syntax error: {line}")
288 if mode
== "options":
289 entries
= line
.split()
290 if len(entries
) != 2:
291 self
.error(f
"sby file syntax error: {line}")
292 self
.options
[entries
[0]] = entries
[1]
295 if mode
== "engines":
296 entries
= line
.split()
297 self
.engines
.append(entries
)
301 self
.script
.append(line
)
305 entries
= line
.split()
306 if len(entries
) == 1:
307 self
.files
[os
.path
.basename(entries
[0])] = entries
[0]
308 elif len(entries
) == 2:
309 self
.files
[entries
[0]] = entries
[1]
311 self
.error(f
"sby file syntax error: {line}")
315 self
.verbatim_files
[current_verbatim_file
].append(raw_line
)
318 self
.error(f
"sby file syntax error: {line}")
320 def error(self
, logmessage
):
321 raise SbyAbort(logmessage
)
323 class SbyTask(SbyConfig
):
324 def __init__(self
, sbyconfig
, workdir
, early_logs
, reusedir
):
326 self
.used_options
= set()
328 self
.workdir
= workdir
329 self
.reusedir
= reusedir
330 self
.status
= "UNKNOWN"
333 self
.design_hierarchy
= None
334 self
.precise_prop_status
= False
336 yosys_program_prefix
= "" ##yosys-program-prefix##
338 "yosys": os
.getenv("YOSYS", yosys_program_prefix
+ "yosys"),
339 "abc": os
.getenv("ABC", yosys_program_prefix
+ "yosys-abc"),
340 "smtbmc": os
.getenv("SMTBMC", yosys_program_prefix
+ "yosys-smtbmc"),
341 "suprove": os
.getenv("SUPROVE", "suprove"),
342 "aigbmc": os
.getenv("AIGBMC", "aigbmc"),
343 "avy": os
.getenv("AVY", "avy"),
344 "btormc": os
.getenv("BTORMC", "btormc"),
345 "pono": os
.getenv("PONO", "pono"),
348 self
.procs_running
= []
349 self
.procs_pending
= []
351 self
.start_clock_time
= time()
353 if os
.name
== "posix":
354 ru
= resource
.getrusage(resource
.RUSAGE_CHILDREN
)
355 self
.start_process_time
= ru
.ru_utime
+ ru
.ru_stime
357 self
.summary
= list()
359 self
.logfile
= open(f
"{workdir}/logfile.txt", "a")
361 for line
in early_logs
:
362 print(line
, file=self
.logfile
, flush
=True)
365 with
open(f
"{workdir}/config.sby", "w") as f
:
366 for line
in sbyconfig
:
370 for proc
in self
.procs_pending
:
373 while len(self
.procs_running
):
375 for proc
in self
.procs_running
:
377 fds
.append(proc
.p
.stdout
)
379 if os
.name
== "posix":
381 select(fds
, [], [], 1.0) == ([], [], [])
382 except InterruptedError
:
387 for proc
in self
.procs_running
:
390 for proc
in self
.procs_pending
:
393 if self
.opt_timeout
is not None:
394 total_clock_time
= int(time() - self
.start_clock_time
)
395 if total_clock_time
> self
.opt_timeout
:
396 self
.log(f
"Reached TIMEOUT ({self.opt_timeout} seconds). Terminating all subprocesses.")
397 self
.status
= "TIMEOUT"
398 self
.terminate(timeout
=True)
400 def log(self
, logmessage
):
402 print("SBY {:2d}:{:02d}:{:02d} [{}] {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), flush
=True)
403 print("SBY {:2d}:{:02d}:{:02d} [{}] {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), file=self
.logfile
, flush
=True)
405 def error(self
, logmessage
):
407 print("SBY {:2d}:{:02d}:{:02d} [{}] ERROR: {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), flush
=True)
408 print("SBY {:2d}:{:02d}:{:02d} [{}] ERROR: {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), file=self
.logfile
, flush
=True)
409 self
.status
= "ERROR"
410 if "ERROR" not in self
.expect
:
415 with
open(f
"{self.workdir}/{self.status}", "w") as f
:
416 print(f
"ERROR: {logmessage}", file=f
)
417 raise SbyAbort(logmessage
)
419 def makedirs(self
, path
):
420 if self
.reusedir
and os
.path
.isdir(path
):
421 rmtree(path
, ignore_errors
=True)
425 os
.makedirs(self
.workdir
+ "/src")
427 for dstfile
, lines
in self
.verbatim_files
.items():
428 dstfile
= self
.workdir
+ "/src/" + dstfile
429 self
.log(f
"Writing '{dstfile}'.")
431 with
open(dstfile
, "w") as f
:
435 for dstfile
, srcfile
in self
.files
.items():
436 if dstfile
.startswith("/") or dstfile
.startswith("../") or ("/../" in dstfile
):
437 self
.error(f
"destination filename must be a relative path without /../: {dstfile}")
438 dstfile
= self
.workdir
+ "/src/" + dstfile
440 srcfile
= process_filename(srcfile
)
442 basedir
= os
.path
.dirname(dstfile
)
443 if basedir
!= "" and not os
.path
.exists(basedir
):
446 self
.log(f
"Copy '{os.path.abspath(srcfile)}' to '{os.path.abspath(dstfile)}'.")
447 if os
.path
.isdir(srcfile
):
448 copytree(srcfile
, dstfile
, dirs_exist_ok
=True)
450 copyfile(srcfile
, dstfile
)
452 def handle_str_option(self
, option_name
, default_value
):
453 if option_name
in self
.options
:
454 self
.__dict
__["opt_" + option_name
] = self
.options
[option_name
]
455 self
.used_options
.add(option_name
)
457 self
.__dict
__["opt_" + option_name
] = default_value
459 def handle_int_option(self
, option_name
, default_value
):
460 if option_name
in self
.options
:
461 self
.__dict
__["opt_" + option_name
] = int(self
.options
[option_name
])
462 self
.used_options
.add(option_name
)
464 self
.__dict
__["opt_" + option_name
] = default_value
466 def handle_bool_option(self
, option_name
, default_value
):
467 if option_name
in self
.options
:
468 if self
.options
[option_name
] not in ["on", "off"]:
469 self
.error(f
"Invalid value '{self.options[option_name]}' for boolean option {option_name}.")
470 self
.__dict
__["opt_" + option_name
] = self
.options
[option_name
] == "on"
471 self
.used_options
.add(option_name
)
473 self
.__dict
__["opt_" + option_name
] = default_value
475 def make_model(self
, model_name
):
476 if not os
.path
.isdir(f
"{self.workdir}/model"):
477 os
.makedirs(f
"{self.workdir}/model")
479 def print_common_prep():
480 if self
.opt_multiclock
:
481 print("clk2fflogic", file=f
)
483 print("async2sync", file=f
)
484 print("chformal -assume -early", file=f
)
485 if self
.opt_mode
in ["bmc", "prove"]:
486 print("chformal -live -fair -cover -remove", file=f
)
487 if self
.opt_mode
== "cover":
488 print("chformal -live -fair -remove", file=f
)
489 if self
.opt_mode
== "live":
490 print("chformal -assert2assume", file=f
)
491 print("chformal -cover -remove", file=f
)
492 print("opt_clean", file=f
)
493 print("setundef -anyseq", file=f
)
494 print("opt -keepdc -fast", file=f
)
495 print("check", file=f
)
496 print("hierarchy -simcheck", file=f
)
498 if model_name
== "base":
499 with
open(f
"""{self.workdir}/model/design.ys""", "w") as f
:
500 print(f
"# running in {self.workdir}/src/", file=f
)
501 for cmd
in self
.script
:
503 # the user must designate a top module in [script]
504 print("hierarchy -simcheck", file=f
)
505 print(f
"""write_jny -no-connections ../model/design.json""", file=f
)
506 print(f
"""write_rtlil ../model/design.il""", file=f
)
512 "cd {}/src; {} -ql ../model/design.log ../model/design.ys".format(self
.workdir
, self
.exe_paths
["yosys"])
514 proc
.checkretcode
= True
516 def instance_hierarchy_callback(retcode
):
517 if self
.design_hierarchy
== None:
518 with
open(f
"{self.workdir}/model/design.json") as f
:
519 self
.design_hierarchy
= design_hierarchy(f
)
521 def instance_hierarchy_error_callback(retcode
):
522 self
.precise_prop_status
= False
524 proc
.exit_callback
= instance_hierarchy_callback
525 proc
.error_callback
= instance_hierarchy_error_callback
529 if re
.match(r
"^smt2(_syn)?(_nomem)?(_stbv|_stdt)?$", model_name
):
530 with
open(f
"{self.workdir}/model/design_{model_name}.ys", "w") as f
:
531 print(f
"# running in {self.workdir}/model/", file=f
)
532 print(f
"""read_ilang design.il""", file=f
)
533 if "_nomem" in model_name
:
534 print("memory_map", file=f
)
536 print("memory_nordff", file=f
)
538 if "_syn" in model_name
:
539 print("techmap", file=f
)
540 print("opt -fast", file=f
)
542 print("opt_clean", file=f
)
543 print("dffunmap", file=f
)
544 print("stat", file=f
)
545 if "_stbv" in model_name
:
546 print(f
"write_smt2 -stbv -wires design_{model_name}.smt2", file=f
)
547 elif "_stdt" in model_name
:
548 print(f
"write_smt2 -stdt -wires design_{model_name}.smt2", file=f
)
550 print(f
"write_smt2 -wires design_{model_name}.smt2", file=f
)
556 "cd {}/model; {} -ql design_{s}.log design_{s}.ys".format(self
.workdir
, self
.exe_paths
["yosys"], s
=model_name
)
558 proc
.checkretcode
= True
562 if re
.match(r
"^btor(_syn)?(_nomem)?$", model_name
):
563 with
open(f
"{self.workdir}/model/design_{model_name}.ys", "w") as f
:
564 print(f
"# running in {self.workdir}/model/", file=f
)
565 print(f
"""read_ilang design.il""", file=f
)
566 if "_nomem" in model_name
:
567 print("memory_map", file=f
)
569 print("memory_nordff", file=f
)
571 print("flatten", file=f
)
572 print("setundef -undriven -anyseq", file=f
)
573 if "_syn" in model_name
:
574 print("opt -full", file=f
)
575 print("techmap", file=f
)
576 print("opt -fast", file=f
)
578 print("opt_clean", file=f
)
580 print("opt -fast", file=f
)
581 print("delete -output", file=f
)
582 print("dffunmap", file=f
)
583 print("stat", file=f
)
584 print("write_btor {}-i design_{m}.info design_{m}.btor".format("-c " if self
.opt_mode
== "cover" else "", m
=model_name
), file=f
)
585 print("write_btor -s {}-i design_{m}_single.info design_{m}_single.btor".format("-c " if self
.opt_mode
== "cover" else "", m
=model_name
), file=f
)
591 "cd {}/model; {} -ql design_{s}.log design_{s}.ys".format(self
.workdir
, self
.exe_paths
["yosys"], s
=model_name
)
593 proc
.checkretcode
= True
597 if model_name
== "aig":
598 with
open(f
"{self.workdir}/model/design_aiger.ys", "w") as f
:
599 print(f
"# running in {self.workdir}/model/", file=f
)
600 print("read_ilang design.il", file=f
)
601 print("memory_map", file=f
)
603 print("flatten", file=f
)
604 print("setundef -undriven -anyseq", file=f
)
605 print("setattr -unset keep", file=f
)
606 print("delete -output", file=f
)
607 print("opt -full", file=f
)
608 print("techmap", file=f
)
609 print("opt -fast", file=f
)
610 print("dffunmap", file=f
)
611 print("abc -g AND -fast", file=f
)
612 print("opt_clean", file=f
)
613 print("stat", file=f
)
614 print("write_aiger -I -B -zinit -no-startoffset -map design_aiger.aim design_aiger.aig", file=f
)
620 f
"""cd {self.workdir}/model; {self.exe_paths["yosys"]} -ql design_aiger.log design_aiger.ys"""
622 proc
.checkretcode
= True
628 def model(self
, model_name
):
629 if model_name
not in self
.models
:
630 self
.models
[model_name
] = self
.make_model(model_name
)
631 return self
.models
[model_name
]
633 def terminate(self
, timeout
=False):
634 for proc
in list(self
.procs_running
):
635 proc
.terminate(timeout
=timeout
)
637 def update_status(self
, new_status
):
638 assert new_status
in ["PASS", "FAIL", "UNKNOWN", "ERROR"]
640 if new_status
== "UNKNOWN":
643 if self
.status
== "ERROR":
646 if new_status
== "PASS":
647 assert self
.status
!= "FAIL"
650 elif new_status
== "FAIL":
651 assert self
.status
!= "PASS"
654 elif new_status
== "ERROR":
655 self
.status
= "ERROR"
660 def run(self
, setupmode
):
661 with
open(f
"{self.workdir}/config.sby", "r") as f
:
664 self
.handle_str_option("mode", None)
666 if self
.opt_mode
not in ["bmc", "prove", "cover", "live"]:
667 self
.error(f
"Invalid mode: {self.opt_mode}")
669 self
.expect
= ["PASS"]
670 if "expect" in self
.options
:
671 self
.expect
= self
.options
["expect"].upper().split(",")
672 self
.used_options
.add("expect")
674 for s
in self
.expect
:
675 if s
not in ["PASS", "FAIL", "UNKNOWN", "ERROR", "TIMEOUT"]:
676 self
.error(f
"Invalid expect value: {s}")
678 self
.handle_bool_option("multiclock", False)
679 self
.handle_bool_option("wait", False)
680 self
.handle_int_option("timeout", None)
682 self
.handle_str_option("smtc", None)
683 self
.handle_int_option("skip", None)
684 self
.handle_str_option("tbtop", None)
686 if self
.opt_smtc
is not None:
687 for engine
in self
.engines
:
688 if engine
[0] != "smtbmc":
689 self
.error("Option smtc is only valid for smtbmc engine.")
691 if self
.opt_skip
is not None:
692 if self
.opt_skip
== 0:
695 for engine
in self
.engines
:
696 if engine
[0] not in ["smtbmc", "btor"]:
697 self
.error("Option skip is only valid for smtbmc and btor engines.")
699 if len(self
.engines
) == 0:
700 self
.error("Config file is lacking engine configuration.")
703 rmtree(f
"{self.workdir}/model", ignore_errors
=True)
711 if self
.opt_mode
== "bmc":
713 sby_mode_bmc
.run(self
)
715 elif self
.opt_mode
== "prove":
716 import sby_mode_prove
717 sby_mode_prove
.run(self
)
719 elif self
.opt_mode
== "live":
721 sby_mode_live
.run(self
)
723 elif self
.opt_mode
== "cover":
724 import sby_mode_cover
725 sby_mode_cover
.run(self
)
730 for opt
in self
.options
.keys():
731 if opt
not in self
.used_options
:
732 self
.error(f
"Unused option: {opt}")
736 total_clock_time
= int(time() - self
.start_clock_time
)
738 if os
.name
== "posix":
739 ru
= resource
.getrusage(resource
.RUSAGE_CHILDREN
)
740 total_process_time
= int((ru
.ru_utime
+ ru
.ru_stime
) - self
.start_process_time
)
741 self
.total_time
= total_process_time
744 "Elapsed clock time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
745 (total_clock_time
// (60*60), (total_clock_time
// 60) % 60, total_clock_time
% 60, total_clock_time
),
746 "Elapsed process time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
747 (total_process_time
// (60*60), (total_process_time
// 60) % 60, total_process_time
% 60, total_process_time
),
751 "Elapsed clock time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
752 (total_clock_time
// (60*60), (total_clock_time
// 60) % 60, total_clock_time
% 60, total_clock_time
),
753 "Elapsed process time unvailable on Windows"
756 for line
in self
.summary
:
757 self
.log(f
"summary: {line}")
759 assert self
.status
in ["PASS", "FAIL", "UNKNOWN", "ERROR", "TIMEOUT"]
761 if self
.status
in self
.expect
:
764 if self
.status
== "PASS": self
.retcode
= 1
765 if self
.status
== "FAIL": self
.retcode
= 2
766 if self
.status
== "UNKNOWN": self
.retcode
= 4
767 if self
.status
== "TIMEOUT": self
.retcode
= 8
768 if self
.status
== "ERROR": self
.retcode
= 16
770 with
open(f
"{self.workdir}/{self.status}", "w") as f
:
771 for line
in self
.summary
:
774 def print_junit_result(self
, f
, junit_ts_name
, junit_tc_name
, junit_format_strict
=False):
775 junit_time
= strftime('%Y-%m-%dT%H:%M:%S')
776 if self
.precise_prop_status
:
777 checks
= self
.design_hierarchy
.get_property_list()
778 junit_tests
= len(checks
)
783 if check
.status
== "PASS":
785 elif check
.status
== "FAIL":
787 elif check
.status
== "UNKNOWN":
791 if self
.retcode
== 16:
793 elif self
.retcode
!= 0:
797 junit_errors
= 1 if self
.retcode
== 16 else 0
798 junit_failures
= 1 if self
.retcode
!= 0 and junit_errors
== 0 else 0
800 print(f
'<?xml version="1.0" encoding="UTF-8"?>', file=f
)
801 print(f
'<testsuites>', file=f
)
802 print(f
'<testsuite timestamp="{junit_time}" hostname="{platform.node()}" package="{junit_ts_name}" id="0" name="{junit_tc_name}" tests="{junit_tests}" errors="{junit_errors}" failures="{junit_failures}" time="{self.total_time}" skipped="{junit_skipped}">', file=f
)
803 print(f
'<properties>', file=f
)
804 print(f
'<property name="os" value="{platform.system()}"/>', file=f
)
805 print(f
'<property name="expect" value="{", ".join(self.expect)}"/>', file=f
)
806 print(f
'<property name="status" value="{self.status}"/>', file=f
)
807 print(f
'</properties>', file=f
)
808 if self
.precise_prop_status
:
809 print(f
'<testcase classname="{junit_tc_name}" name="build execution" time="0">', file=f
)
810 if self
.retcode
== 16:
811 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
812 elif self
.retcode
!= 0:
813 if len(self
.expect
) > 1 or "PASS" not in self
.expect
:
814 expected
= " ".join(self
.expect
)
815 print(f
'<failure type="EXPECT" message="Task returned status {self.status}. Expected values were: {expected}" />', file=f
)
817 print(f
'<failure type="{self.status}" message="Task returned status {self.status}." />', file=f
)
818 print(f
'</testcase>', file=f
)
821 if junit_format_strict
:
824 detail_attrs
= f
' type="{check.type}" location="{check.location}" id="{check.name}"'
826 detail_attrs
+= f
' tracefile="{check.tracefile}"'
828 junit_prop_name
= f
"Property {check.type} in {check.hierarchy} at {check.location}"
830 junit_prop_name
= f
"Property {check.type} {check.name} in {check.hierarchy}"
831 print(f
'<testcase classname="{junit_tc_name}" name="{junit_prop_name}" time="0"{detail_attrs}>', file=f
)
832 if check
.status
== "PASS":
834 elif check
.status
== "UNKNOWN":
835 print(f
'<skipped />', file=f
)
836 elif check
.status
== "FAIL":
837 traceinfo
= f
' Trace file: {check.tracefile}' if check
.type == check
.Type
.ASSERT
else ''
838 print(f
'<failure type="{check.type}" message="{junit_prop_name} failed.{traceinfo}" />', file=f
)
839 elif check
.status
== "ERROR":
840 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
841 print(f
'</testcase>', file=f
)
843 print(f
'<testcase classname="{junit_tc_name}" name="{junit_tc_name}" time="{self.total_time}">', file=f
)
845 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
847 junit_type
= "assert" if self
.opt_mode
in ["bmc", "prove"] else self
.opt_mode
848 print(f
'<failure type="{junit_type}" message="{self.status}" />', file=f
)
849 print(f
'</testcase>', file=f
)
850 print('<system-out>', end
="", file=f
)
851 with
open(f
"{self.workdir}/logfile.txt", "r") as logf
:
853 print(line
.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """), end
="", file=f
)
854 print('</system-out>', file=f
)
855 print('<system-err>', file=f
)
856 #TODO: can we handle errors and still output this file?
857 print('</system-err>', file=f
)
858 print(f
'</testsuite>', file=f
)
859 print(f
'</testsuites>', file=f
)