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 monotonic
, 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
59 if os
.name
== "posix":
60 self
.cmdline
= cmdline
62 # Windows command interpreter equivalents for sequential
63 # commands (; => &) command grouping ({} => ()).
69 parts
= cmdline
.split("'")
70 for i
in range(len(parts
)):
72 cmdline_copy
= parts
[i
]
73 for u
, w
in replacements
.items():
74 cmdline_copy
= cmdline_copy
.replace(u
, w
)
75 parts
[i
] = cmdline_copy
76 self
.cmdline
= '"'.join(parts
)
77 self
.logfile
= logfile
78 self
.noprintregex
= None
81 self
.logstderr
= logstderr
84 self
.task
.procs_pending
.append(self
)
87 dep
.register_dep(self
)
89 self
.output_callback
= None
90 self
.exit_callback
= None
91 self
.error_callback
= None
93 def register_dep(self
, next_proc
):
97 self
.notify
.append(next_proc
)
100 if line
is not None and (self
.noprintregex
is None or not self
.noprintregex
.match(line
)):
101 if self
.logfile
is not None:
102 print(line
, file=self
.logfile
)
103 self
.task
.log(f
"{self.info}: {line}")
105 def handle_output(self
, line
):
106 if self
.terminated
or len(line
) == 0:
108 if self
.output_callback
is not None:
109 line
= self
.output_callback(line
)
112 def handle_exit(self
, retcode
):
115 if self
.logfile
is not None:
117 if self
.exit_callback
is not None:
118 self
.exit_callback(retcode
)
120 def handle_error(self
, retcode
):
123 if self
.logfile
is not None:
125 if self
.error_callback
is not None:
126 self
.error_callback(retcode
)
128 def terminate(self
, timeout
=False):
129 if self
.task
.opt_wait
and not timeout
:
133 self
.task
.log(f
"{self.info}: terminating process")
134 if os
.name
== "posix":
136 os
.killpg(self
.p
.pid
, signal
.SIGTERM
)
137 except PermissionError
:
140 self
.task
.procs_running
.remove(self
)
141 all_procs_running
.remove(self
)
142 self
.terminated
= True
145 if self
.finished
or self
.terminated
:
149 for dep
in self
.deps
:
154 self
.task
.log(f
"{self.info}: starting process \"{self.cmdline}\"")
156 if os
.name
== "posix":
158 signal
.signal(signal
.SIGINT
, signal
.SIG_IGN
)
161 self
.p
= subprocess
.Popen(["/usr/bin/env", "bash", "-c", self
.cmdline
], stdin
=subprocess
.DEVNULL
, stdout
=subprocess
.PIPE
,
162 stderr
=(subprocess
.STDOUT
if self
.logstderr
else None), preexec_fn
=preexec_fn
)
164 fl
= fcntl
.fcntl(self
.p
.stdout
, fcntl
.F_GETFL
)
165 fcntl
.fcntl(self
.p
.stdout
, fcntl
.F_SETFL
, fl | os
.O_NONBLOCK
)
168 self
.p
= subprocess
.Popen(self
.cmdline
, shell
=True, stdin
=subprocess
.DEVNULL
, stdout
=subprocess
.PIPE
,
169 stderr
=(subprocess
.STDOUT
if self
.logstderr
else None))
171 self
.task
.procs_pending
.remove(self
)
172 self
.task
.procs_running
.append(self
)
173 all_procs_running
.append(self
)
178 outs
= self
.p
.stdout
.readline().decode("utf-8")
179 if len(outs
) == 0: break
181 self
.linebuffer
+= outs
183 outs
= (self
.linebuffer
+ outs
).strip()
185 self
.handle_output(outs
)
187 if self
.p
.poll() is not None:
189 self
.task
.log(f
"{self.info}: finished (returncode={self.p.returncode})")
190 self
.task
.procs_running
.remove(self
)
191 all_procs_running
.remove(self
)
194 if self
.p
.returncode
== 127:
195 self
.task
.status
= "ERROR"
197 self
.task
.log(f
"{self.info}: COMMAND NOT FOUND. ERROR.")
198 self
.handle_error(self
.p
.returncode
)
199 self
.terminated
= True
200 self
.task
.terminate()
203 if self
.checkretcode
and self
.p
.returncode
not in self
.retcodes
:
204 self
.task
.status
= "ERROR"
206 self
.task
.log(f
"{self.info}: task failed. ERROR.")
207 self
.handle_error(self
.p
.returncode
)
208 self
.terminated
= True
209 self
.task
.terminate()
212 self
.handle_exit(self
.p
.returncode
)
215 for next_proc
in self
.notify
:
220 class SbyAbort(BaseException
):
226 self
.options
= dict()
227 self
.engines
= list()
230 self
.verbatim_files
= dict()
233 def parse_config(self
, f
):
238 if mode
in ["options", "engines", "files"]:
239 line
= re
.sub(r
"\s*(\s#.*)?$", "", line
)
240 if line
== "" or line
[0] == "#":
245 if mode
is None and (len(line
) == 0 or line
[0] == "#"):
247 match
= re
.match(r
"^\s*\[(.*)\]\s*$", line
)
249 entries
= match
.group(1).split()
250 if len(entries
) == 0:
251 self
.error(f
"sby file syntax error: {line}")
253 if entries
[0] == "options":
255 if len(self
.options
) != 0 or len(entries
) != 1:
256 self
.error(f
"sby file syntax error: {line}")
259 if entries
[0] == "engines":
261 if len(self
.engines
) != 0 or len(entries
) != 1:
262 self
.error(f
"sby file syntax error: {line}")
265 if entries
[0] == "script":
267 if len(self
.script
) != 0 or len(entries
) != 1:
268 self
.error(f
"sby file syntax error: {line}")
271 if entries
[0] == "file":
273 if len(entries
) != 2:
274 self
.error(f
"sby file syntax error: {line}")
275 current_verbatim_file
= entries
[1]
276 if current_verbatim_file
in self
.verbatim_files
:
277 self
.error(f
"duplicate file: {entries[1]}")
278 self
.verbatim_files
[current_verbatim_file
] = list()
281 if entries
[0] == "files":
283 if len(entries
) != 1:
284 self
.error(f
"sby file syntax error: {line}")
287 self
.error(f
"sby file syntax error: {line}")
289 if mode
== "options":
290 entries
= line
.split()
291 if len(entries
) != 2:
292 self
.error(f
"sby file syntax error: {line}")
293 self
.options
[entries
[0]] = entries
[1]
296 if mode
== "engines":
297 entries
= line
.split()
298 self
.engines
.append(entries
)
302 self
.script
.append(line
)
306 entries
= line
.split()
307 if len(entries
) == 1:
308 self
.files
[os
.path
.basename(entries
[0])] = entries
[0]
309 elif len(entries
) == 2:
310 self
.files
[entries
[0]] = entries
[1]
312 self
.error(f
"sby file syntax error: {line}")
316 self
.verbatim_files
[current_verbatim_file
].append(raw_line
)
319 self
.error(f
"sby file syntax error: {line}")
321 def error(self
, logmessage
):
322 raise SbyAbort(logmessage
)
324 class SbyTask(SbyConfig
):
325 def __init__(self
, sbyconfig
, workdir
, early_logs
, reusedir
):
327 self
.used_options
= set()
329 self
.workdir
= workdir
330 self
.reusedir
= reusedir
331 self
.status
= "UNKNOWN"
334 self
.design_hierarchy
= None
335 self
.precise_prop_status
= False
337 yosys_program_prefix
= "" ##yosys-program-prefix##
339 "yosys": os
.getenv("YOSYS", yosys_program_prefix
+ "yosys"),
340 "abc": os
.getenv("ABC", yosys_program_prefix
+ "yosys-abc"),
341 "smtbmc": os
.getenv("SMTBMC", yosys_program_prefix
+ "yosys-smtbmc"),
342 "suprove": os
.getenv("SUPROVE", "suprove"),
343 "aigbmc": os
.getenv("AIGBMC", "aigbmc"),
344 "avy": os
.getenv("AVY", "avy"),
345 "btormc": os
.getenv("BTORMC", "btormc"),
346 "pono": os
.getenv("PONO", "pono"),
349 self
.procs_running
= []
350 self
.procs_pending
= []
352 self
.start_clock_time
= monotonic()
354 if os
.name
== "posix":
355 ru
= resource
.getrusage(resource
.RUSAGE_CHILDREN
)
356 self
.start_process_time
= ru
.ru_utime
+ ru
.ru_stime
358 self
.summary
= list()
360 self
.logfile
= open(f
"{workdir}/logfile.txt", "a")
362 for line
in early_logs
:
363 print(line
, file=self
.logfile
, flush
=True)
366 with
open(f
"{workdir}/config.sby", "w") as f
:
367 for line
in sbyconfig
:
371 for proc
in self
.procs_pending
:
374 while len(self
.procs_running
):
376 for proc
in self
.procs_running
:
378 fds
.append(proc
.p
.stdout
)
380 if os
.name
== "posix":
382 select(fds
, [], [], 1.0) == ([], [], [])
383 except InterruptedError
:
388 for proc
in self
.procs_running
:
391 for proc
in self
.procs_pending
:
394 if self
.opt_timeout
is not None:
395 total_clock_time
= int(monotonic() - self
.start_clock_time
)
396 if total_clock_time
> self
.opt_timeout
:
397 self
.log(f
"Reached TIMEOUT ({self.opt_timeout} seconds). Terminating all subprocesses.")
398 self
.status
= "TIMEOUT"
399 self
.terminate(timeout
=True)
401 def log(self
, logmessage
):
403 print("SBY {:2d}:{:02d}:{:02d} [{}] {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), flush
=True)
404 print("SBY {:2d}:{:02d}:{:02d} [{}] {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), file=self
.logfile
, flush
=True)
406 def error(self
, logmessage
):
408 print("SBY {:2d}:{:02d}:{:02d} [{}] ERROR: {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), flush
=True)
409 print("SBY {:2d}:{:02d}:{:02d} [{}] ERROR: {}".format(tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, self
.workdir
, logmessage
), file=self
.logfile
, flush
=True)
410 self
.status
= "ERROR"
411 if "ERROR" not in self
.expect
:
416 with
open(f
"{self.workdir}/{self.status}", "w") as f
:
417 print(f
"ERROR: {logmessage}", file=f
)
418 raise SbyAbort(logmessage
)
420 def makedirs(self
, path
):
421 if self
.reusedir
and os
.path
.isdir(path
):
422 rmtree(path
, ignore_errors
=True)
426 os
.makedirs(self
.workdir
+ "/src")
428 for dstfile
, lines
in self
.verbatim_files
.items():
429 dstfile
= self
.workdir
+ "/src/" + dstfile
430 self
.log(f
"Writing '{dstfile}'.")
432 with
open(dstfile
, "w") as f
:
436 for dstfile
, srcfile
in self
.files
.items():
437 if dstfile
.startswith("/") or dstfile
.startswith("../") or ("/../" in dstfile
):
438 self
.error(f
"destination filename must be a relative path without /../: {dstfile}")
439 dstfile
= self
.workdir
+ "/src/" + dstfile
441 srcfile
= process_filename(srcfile
)
443 basedir
= os
.path
.dirname(dstfile
)
444 if basedir
!= "" and not os
.path
.exists(basedir
):
447 self
.log(f
"Copy '{os.path.abspath(srcfile)}' to '{os.path.abspath(dstfile)}'.")
448 if os
.path
.isdir(srcfile
):
449 copytree(srcfile
, dstfile
, dirs_exist_ok
=True)
451 copyfile(srcfile
, dstfile
)
453 def handle_str_option(self
, option_name
, default_value
):
454 if option_name
in self
.options
:
455 self
.__dict
__["opt_" + option_name
] = self
.options
[option_name
]
456 self
.used_options
.add(option_name
)
458 self
.__dict
__["opt_" + option_name
] = default_value
460 def handle_int_option(self
, option_name
, default_value
):
461 if option_name
in self
.options
:
462 self
.__dict
__["opt_" + option_name
] = int(self
.options
[option_name
])
463 self
.used_options
.add(option_name
)
465 self
.__dict
__["opt_" + option_name
] = default_value
467 def handle_bool_option(self
, option_name
, default_value
):
468 if option_name
in self
.options
:
469 if self
.options
[option_name
] not in ["on", "off"]:
470 self
.error(f
"Invalid value '{self.options[option_name]}' for boolean option {option_name}.")
471 self
.__dict
__["opt_" + option_name
] = self
.options
[option_name
] == "on"
472 self
.used_options
.add(option_name
)
474 self
.__dict
__["opt_" + option_name
] = default_value
476 def make_model(self
, model_name
):
477 if not os
.path
.isdir(f
"{self.workdir}/model"):
478 os
.makedirs(f
"{self.workdir}/model")
480 def print_common_prep():
481 if self
.opt_multiclock
:
482 print("clk2fflogic", file=f
)
484 print("async2sync", file=f
)
485 print("chformal -assume -early", file=f
)
486 if self
.opt_mode
in ["bmc", "prove"]:
487 print("chformal -live -fair -cover -remove", file=f
)
488 if self
.opt_mode
== "cover":
489 print("chformal -live -fair -remove", file=f
)
490 if self
.opt_mode
== "live":
491 print("chformal -assert2assume", file=f
)
492 print("chformal -cover -remove", file=f
)
493 print("opt_clean", file=f
)
494 print("setundef -anyseq", file=f
)
495 print("opt -keepdc -fast", file=f
)
496 print("check", file=f
)
497 print("hierarchy -simcheck", file=f
)
499 if model_name
== "base":
500 with
open(f
"""{self.workdir}/model/design.ys""", "w") as f
:
501 print(f
"# running in {self.workdir}/src/", file=f
)
502 for cmd
in self
.script
:
504 # the user must designate a top module in [script]
505 print("hierarchy -simcheck", file=f
)
506 print(f
"""write_jny -no-connections ../model/design.json""", file=f
)
507 print(f
"""write_rtlil ../model/design.il""", file=f
)
513 "cd {}/src; {} -ql ../model/design.log ../model/design.ys".format(self
.workdir
, self
.exe_paths
["yosys"])
515 proc
.checkretcode
= True
517 def instance_hierarchy_callback(retcode
):
518 if self
.design_hierarchy
== None:
519 with
open(f
"{self.workdir}/model/design.json") as f
:
520 self
.design_hierarchy
= design_hierarchy(f
)
522 def instance_hierarchy_error_callback(retcode
):
523 self
.precise_prop_status
= False
525 proc
.exit_callback
= instance_hierarchy_callback
526 proc
.error_callback
= instance_hierarchy_error_callback
530 if re
.match(r
"^smt2(_syn)?(_nomem)?(_stbv|_stdt)?$", model_name
):
531 with
open(f
"{self.workdir}/model/design_{model_name}.ys", "w") as f
:
532 print(f
"# running in {self.workdir}/model/", file=f
)
533 print(f
"""read_ilang design.il""", file=f
)
534 if "_nomem" in model_name
:
535 print("memory_map", file=f
)
537 print("memory_nordff", file=f
)
539 if "_syn" in model_name
:
540 print("techmap", file=f
)
541 print("opt -fast", file=f
)
543 print("opt_clean", file=f
)
544 print("dffunmap", file=f
)
545 print("stat", file=f
)
546 if "_stbv" in model_name
:
547 print(f
"write_smt2 -stbv -wires design_{model_name}.smt2", file=f
)
548 elif "_stdt" in model_name
:
549 print(f
"write_smt2 -stdt -wires design_{model_name}.smt2", file=f
)
551 print(f
"write_smt2 -wires design_{model_name}.smt2", file=f
)
557 "cd {}/model; {} -ql design_{s}.log design_{s}.ys".format(self
.workdir
, self
.exe_paths
["yosys"], s
=model_name
)
559 proc
.checkretcode
= True
563 if re
.match(r
"^btor(_syn)?(_nomem)?$", model_name
):
564 with
open(f
"{self.workdir}/model/design_{model_name}.ys", "w") as f
:
565 print(f
"# running in {self.workdir}/model/", file=f
)
566 print(f
"""read_ilang design.il""", file=f
)
567 if "_nomem" in model_name
:
568 print("memory_map", file=f
)
570 print("memory_nordff", file=f
)
572 print("flatten", file=f
)
573 print("setundef -undriven -anyseq", file=f
)
574 if "_syn" in model_name
:
575 print("opt -full", file=f
)
576 print("techmap", file=f
)
577 print("opt -fast", file=f
)
579 print("opt_clean", file=f
)
581 print("opt -fast", file=f
)
582 print("delete -output", file=f
)
583 print("dffunmap", file=f
)
584 print("stat", file=f
)
585 print("write_btor {}-i design_{m}.info design_{m}.btor".format("-c " if self
.opt_mode
== "cover" else "", m
=model_name
), file=f
)
586 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
)
592 "cd {}/model; {} -ql design_{s}.log design_{s}.ys".format(self
.workdir
, self
.exe_paths
["yosys"], s
=model_name
)
594 proc
.checkretcode
= True
598 if model_name
== "aig":
599 with
open(f
"{self.workdir}/model/design_aiger.ys", "w") as f
:
600 print(f
"# running in {self.workdir}/model/", file=f
)
601 print("read_ilang design.il", file=f
)
602 print("memory_map", file=f
)
604 print("flatten", file=f
)
605 print("setundef -undriven -anyseq", file=f
)
606 print("setattr -unset keep", file=f
)
607 print("delete -output", file=f
)
608 print("opt -full", file=f
)
609 print("techmap", file=f
)
610 print("opt -fast", file=f
)
611 print("dffunmap", file=f
)
612 print("abc -g AND -fast", file=f
)
613 print("opt_clean", file=f
)
614 print("stat", file=f
)
615 print("write_aiger -I -B -zinit -no-startoffset -map design_aiger.aim design_aiger.aig", file=f
)
621 f
"""cd {self.workdir}/model; {self.exe_paths["yosys"]} -ql design_aiger.log design_aiger.ys"""
623 proc
.checkretcode
= True
629 def model(self
, model_name
):
630 if model_name
not in self
.models
:
631 self
.models
[model_name
] = self
.make_model(model_name
)
632 return self
.models
[model_name
]
634 def terminate(self
, timeout
=False):
635 for proc
in list(self
.procs_running
):
636 proc
.terminate(timeout
=timeout
)
638 def update_status(self
, new_status
):
639 assert new_status
in ["PASS", "FAIL", "UNKNOWN", "ERROR"]
641 if new_status
== "UNKNOWN":
644 if self
.status
== "ERROR":
647 if new_status
== "PASS":
648 assert self
.status
!= "FAIL"
651 elif new_status
== "FAIL":
652 assert self
.status
!= "PASS"
655 elif new_status
== "ERROR":
656 self
.status
= "ERROR"
661 def run(self
, setupmode
):
662 with
open(f
"{self.workdir}/config.sby", "r") as f
:
665 self
.handle_str_option("mode", None)
667 if self
.opt_mode
not in ["bmc", "prove", "cover", "live"]:
668 self
.error(f
"Invalid mode: {self.opt_mode}")
670 self
.expect
= ["PASS"]
671 if "expect" in self
.options
:
672 self
.expect
= self
.options
["expect"].upper().split(",")
673 self
.used_options
.add("expect")
675 for s
in self
.expect
:
676 if s
not in ["PASS", "FAIL", "UNKNOWN", "ERROR", "TIMEOUT"]:
677 self
.error(f
"Invalid expect value: {s}")
679 self
.handle_bool_option("multiclock", False)
680 self
.handle_bool_option("wait", False)
681 self
.handle_int_option("timeout", None)
683 self
.handle_str_option("smtc", None)
684 self
.handle_int_option("skip", None)
685 self
.handle_str_option("tbtop", None)
687 if self
.opt_smtc
is not None:
688 for engine
in self
.engines
:
689 if engine
[0] != "smtbmc":
690 self
.error("Option smtc is only valid for smtbmc engine.")
692 if self
.opt_skip
is not None:
693 if self
.opt_skip
== 0:
696 for engine
in self
.engines
:
697 if engine
[0] not in ["smtbmc", "btor"]:
698 self
.error("Option skip is only valid for smtbmc and btor engines.")
700 if len(self
.engines
) == 0:
701 self
.error("Config file is lacking engine configuration.")
704 rmtree(f
"{self.workdir}/model", ignore_errors
=True)
712 if self
.opt_mode
== "bmc":
714 sby_mode_bmc
.run(self
)
716 elif self
.opt_mode
== "prove":
717 import sby_mode_prove
718 sby_mode_prove
.run(self
)
720 elif self
.opt_mode
== "live":
722 sby_mode_live
.run(self
)
724 elif self
.opt_mode
== "cover":
725 import sby_mode_cover
726 sby_mode_cover
.run(self
)
731 for opt
in self
.options
.keys():
732 if opt
not in self
.used_options
:
733 self
.error(f
"Unused option: {opt}")
737 total_clock_time
= int(monotonic() - self
.start_clock_time
)
739 if os
.name
== "posix":
740 ru
= resource
.getrusage(resource
.RUSAGE_CHILDREN
)
741 total_process_time
= int((ru
.ru_utime
+ ru
.ru_stime
) - self
.start_process_time
)
742 self
.total_time
= total_process_time
745 "Elapsed clock time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
746 (total_clock_time
// (60*60), (total_clock_time
// 60) % 60, total_clock_time
% 60, total_clock_time
),
747 "Elapsed process time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
748 (total_process_time
// (60*60), (total_process_time
// 60) % 60, total_process_time
% 60, total_process_time
),
752 "Elapsed clock time [H:MM:SS (secs)]: {}:{:02d}:{:02d} ({})".format
753 (total_clock_time
// (60*60), (total_clock_time
// 60) % 60, total_clock_time
% 60, total_clock_time
),
754 "Elapsed process time unvailable on Windows"
757 for line
in self
.summary
:
758 self
.log(f
"summary: {line}")
760 assert self
.status
in ["PASS", "FAIL", "UNKNOWN", "ERROR", "TIMEOUT"]
762 if self
.status
in self
.expect
:
765 if self
.status
== "PASS": self
.retcode
= 1
766 if self
.status
== "FAIL": self
.retcode
= 2
767 if self
.status
== "UNKNOWN": self
.retcode
= 4
768 if self
.status
== "TIMEOUT": self
.retcode
= 8
769 if self
.status
== "ERROR": self
.retcode
= 16
771 with
open(f
"{self.workdir}/{self.status}", "w") as f
:
772 for line
in self
.summary
:
775 def print_junit_result(self
, f
, junit_ts_name
, junit_tc_name
, junit_format_strict
=False):
776 junit_time
= strftime('%Y-%m-%dT%H:%M:%S')
777 if self
.precise_prop_status
:
778 checks
= self
.design_hierarchy
.get_property_list()
779 junit_tests
= len(checks
)
784 if check
.status
== "PASS":
786 elif check
.status
== "FAIL":
788 elif check
.status
== "UNKNOWN":
792 if self
.retcode
== 16:
794 elif self
.retcode
!= 0:
798 junit_errors
= 1 if self
.retcode
== 16 else 0
799 junit_failures
= 1 if self
.retcode
!= 0 and junit_errors
== 0 else 0
801 print(f
'<?xml version="1.0" encoding="UTF-8"?>', file=f
)
802 print(f
'<testsuites>', file=f
)
803 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
)
804 print(f
'<properties>', file=f
)
805 print(f
'<property name="os" value="{platform.system()}"/>', file=f
)
806 print(f
'<property name="expect" value="{", ".join(self.expect)}"/>', file=f
)
807 print(f
'<property name="status" value="{self.status}"/>', file=f
)
808 print(f
'</properties>', file=f
)
809 if self
.precise_prop_status
:
810 print(f
'<testcase classname="{junit_tc_name}" name="build execution" time="0">', file=f
)
811 if self
.retcode
== 16:
812 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
813 elif self
.retcode
!= 0:
814 if len(self
.expect
) > 1 or "PASS" not in self
.expect
:
815 expected
= " ".join(self
.expect
)
816 print(f
'<failure type="EXPECT" message="Task returned status {self.status}. Expected values were: {expected}" />', file=f
)
818 print(f
'<failure type="{self.status}" message="Task returned status {self.status}." />', file=f
)
819 print(f
'</testcase>', file=f
)
822 if junit_format_strict
:
825 detail_attrs
= f
' type="{check.type}" location="{check.location}" id="{check.name}"'
827 detail_attrs
+= f
' tracefile="{check.tracefile}"'
829 junit_prop_name
= f
"Property {check.type} in {check.hierarchy} at {check.location}"
831 junit_prop_name
= f
"Property {check.type} {check.name} in {check.hierarchy}"
832 print(f
'<testcase classname="{junit_tc_name}" name="{junit_prop_name}" time="0"{detail_attrs}>', file=f
)
833 if check
.status
== "PASS":
835 elif check
.status
== "UNKNOWN":
836 print(f
'<skipped />', file=f
)
837 elif check
.status
== "FAIL":
838 traceinfo
= f
' Trace file: {check.tracefile}' if check
.type == check
.Type
.ASSERT
else ''
839 print(f
'<failure type="{check.type}" message="{junit_prop_name} failed.{traceinfo}" />', file=f
)
840 elif check
.status
== "ERROR":
841 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
842 print(f
'</testcase>', file=f
)
844 print(f
'<testcase classname="{junit_tc_name}" name="{junit_tc_name}" time="{self.total_time}">', file=f
)
846 print(f
'<error type="ERROR"/>', file=f
) # type mandatory, message optional
848 junit_type
= "assert" if self
.opt_mode
in ["bmc", "prove"] else self
.opt_mode
849 print(f
'<failure type="{junit_type}" message="{self.status}" />', file=f
)
850 print(f
'</testcase>', file=f
)
851 print('<system-out>', end
="", file=f
)
852 with
open(f
"{self.workdir}/logfile.txt", "r") as logf
:
854 print(line
.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """), end
="", file=f
)
855 print('</system-out>', file=f
)
856 print('<system-err>', file=f
)
857 #TODO: can we handle errors and still output this file?
858 print('</system-err>', file=f
)
859 print(f
'</testsuite>', file=f
)
860 print(f
'</testsuites>', file=f
)