-
Notifications
You must be signed in to change notification settings - Fork 78
/
sby_core.py
1505 lines (1244 loc) · 58.9 KB
/
sby_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# SymbiYosys (sby) -- Front-end for Yosys-based formal verification flows
#
# Copyright (C) 2016 Claire Xenia Wolf <claire@yosyshq.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
import os, re, sys, signal, platform, click
if os.name == "posix":
import resource, fcntl
import subprocess
from dataclasses import dataclass, field
from collections import defaultdict
from typing import Optional
from shutil import copyfile, copytree, rmtree
from select import select
from time import monotonic, localtime, sleep, strftime
from sby_design import SbyProperty, SbyModule, design_hierarchy
from sby_status import SbyStatusDb
all_procs_running = []
def force_shutdown(signum, frame):
click.echo("SBY ---- Keyboard interrupt or external termination signal ----")
for proc in list(all_procs_running):
proc.terminate()
sys.exit(1)
if os.name == "posix":
signal.signal(signal.SIGHUP, force_shutdown)
signal.signal(signal.SIGINT, force_shutdown)
signal.signal(signal.SIGTERM, force_shutdown)
def process_filename(filename):
if filename.startswith("~/"):
filename = os.environ['HOME'] + filename[1:]
filename = os.path.expandvars(filename)
return filename
def dress_message(workdir, logmessage):
tm = localtime()
if workdir is not None:
logmessage = "[" + click.style(workdir, fg="blue") + "] " + logmessage
return " ".join([
click.style("SBY", fg="blue"),
click.style("{:2d}:{:02d}:{:02d}".format(tm.tm_hour, tm.tm_min, tm.tm_sec), fg="green"),
logmessage
])
class SbyProc:
def __init__(self, task, info, deps, cmdline, logfile=None, logstderr=True, silent=False):
self.running = False
self.finished = False
self.terminated = False
self.exited = False
self.checkretcode = False
self.retcodes = [0]
self.task = task
self.info = info
self.deps = deps
if os.name == "posix":
self.cmdline = cmdline
else:
# Windows command interpreter equivalents for sequential
# commands (; => &) command grouping ({} => ()).
replacements = {
";" : "&",
"{" : "(",
"}" : ")",
}
parts = cmdline.split("'")
for i in range(len(parts)):
if i % 2 == 0:
cmdline_copy = parts[i]
for u, w in replacements.items():
cmdline_copy = cmdline_copy.replace(u, w)
parts[i] = cmdline_copy
self.cmdline = '"'.join(parts)
self.logfile = logfile
self.noprintregex = None
self.notify = []
self.linebuffer = ""
self.logstderr = logstderr
self.silent = silent
self.wait = False
self.job_lease = None
self.task.update_proc_pending(self)
for dep in self.deps:
dep.register_dep(self)
self.output_callback = None
self.exit_callbacks = []
self.error_callback = None
if self.task.timeout_reached:
self.terminate(True)
def register_dep(self, next_proc):
if self.finished:
next_proc.poll()
else:
self.notify.append(next_proc)
def register_exit_callback(self, callback):
self.exit_callbacks.append(callback)
def log(self, line):
if line is not None and (self.noprintregex is None or not self.noprintregex.match(line)):
if self.logfile is not None:
click.echo(line, file=self.logfile)
self.task.log(f"{click.style(self.info, fg='magenta')}: {line}")
def handle_output(self, line):
if self.terminated or len(line) == 0:
return
if self.output_callback is not None:
line = self.output_callback(line)
self.log(line)
def handle_exit(self, retcode):
if self.terminated:
return
if self.logfile is not None:
self.logfile.close()
for callback in self.exit_callbacks:
callback(retcode)
def handle_error(self, retcode):
if self.terminated:
return
if self.logfile is not None:
self.logfile.close()
if self.error_callback is not None:
self.error_callback(retcode)
def terminate(self, timeout=False):
if (self.task.opt_wait or self.wait) and not timeout:
return
if self.running:
if not self.silent:
self.task.log(f"{click.style(self.info, fg='magenta')}: terminating process")
if os.name == "posix":
try:
os.killpg(self.p.pid, signal.SIGTERM)
except PermissionError:
pass
self.p.terminate()
self.task.update_proc_stopped(self)
elif not self.finished and not self.terminated and not self.exited:
self.task.update_proc_canceled(self)
self.terminated = True
def poll(self, force_unchecked=False):
if self.task.task_local_abort and not force_unchecked:
try:
self.poll(True)
except SbyAbort:
self.task.terminate(True)
return
if self.finished or self.terminated or self.exited:
return
if not self.running:
for dep in self.deps:
if not dep.finished:
return
if self.task.taskloop.jobclient:
if self.job_lease is None:
self.job_lease = self.task.taskloop.jobclient.request_lease()
if not self.job_lease.is_ready:
return
if not self.silent:
self.task.log(f"{click.style(self.info, fg='magenta')}: starting process \"{self.cmdline}\"")
if os.name == "posix":
def preexec_fn():
signal.signal(signal.SIGINT, signal.SIG_IGN)
os.setpgrp()
self.p = subprocess.Popen(["/usr/bin/env", "bash", "-c", self.cmdline], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=(subprocess.STDOUT if self.logstderr else None), preexec_fn=preexec_fn)
fl = fcntl.fcntl(self.p.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.p.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
else:
self.p = subprocess.Popen(self.cmdline + " & exit !errorlevel!", shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=(subprocess.STDOUT if self.logstderr else None))
self.task.update_proc_running(self)
self.running = True
return
self.read_output()
if self.p.poll() is not None:
# The process might have written something since the last time we checked
self.read_output()
if self.job_lease:
self.job_lease.done()
if not self.silent:
self.task.log(f"{click.style(self.info, fg='magenta')}: finished (returncode={self.p.returncode})")
self.task.update_proc_stopped(self)
self.running = False
self.exited = True
if os.name == "nt":
if self.p.returncode == 9009:
returncode = 127
else:
returncode = self.p.returncode & 0xff
else:
returncode = self.p.returncode
if returncode == 127:
if not self.silent:
self.task.log(f"{click.style(self.info, fg='magenta')}: COMMAND NOT FOUND. ERROR.")
self.handle_error(returncode)
self.terminated = True
self.task.proc_failed(self)
return
if self.checkretcode and returncode not in self.retcodes:
if not self.silent:
self.task.log(f"{click.style(self.info, fg='magenta')}: task failed. ERROR.")
self.handle_error(returncode)
self.terminated = True
self.task.proc_failed(self)
return
self.handle_exit(returncode)
self.finished = True
for next_proc in self.notify:
next_proc.poll()
return
def read_output(self):
while True:
outs = self.p.stdout.readline().decode("utf-8")
if len(outs) == 0: break
if outs[-1] != '\n':
self.linebuffer += outs
break
outs = (self.linebuffer + outs).strip()
self.linebuffer = ""
self.handle_output(outs)
class SbyAbort(BaseException):
pass
class SbyConfig:
def __init__(self):
self.options = dict()
self.engines = dict()
self.setup = dict()
self.stage = dict()
self.script = list()
self.autotune_config = None
self.files = dict()
self.verbatim_files = dict()
pass
def parse_config(self, f):
mode = None
engine_mode = None
stage_name = None
for line in f:
raw_line = line
if mode in ["options", "engines", "files", "autotune", "setup", "stage"]:
line = re.sub(r"\s*(\s#.*)?$", "", line)
if line == "" or line[0] == "#":
continue
else:
line = line.rstrip()
# print(line)
if mode is None and (len(line) == 0 or line[0] == "#"):
continue
match = re.match(r"^\s*\[(.*)\]\s*$", line)
if match:
entries = match.group(1).strip().split(maxsplit = 1)
if len(entries) == 0:
self.error(f"sby file syntax error: Expected section header, got '{line}'")
elif len(entries) == 1:
section, args = (*entries, None)
else:
section, args = entries
if section == "options":
mode = "options"
if len(self.options) != 0:
self.error(f"sby file syntax error: '[options]' section already defined")
if args is not None:
self.error(f"sby file syntax error: '[options]' section does not accept any arguments. got {args}")
continue
if section == "engines":
mode = "engines"
if args is None:
engine_mode = None
else:
section_args = args.split()
if len(section_args) > 1:
self.error(f"sby file syntax error: '[engines]' section expects at most 1 argument, got '{' '.join(section_args)}'")
if section_args[0] not in ("bmc", "prove", "cover", "live"):
self.error(f"sby file syntax error: Expected one of 'bmc', 'prove', 'cover', 'live' as '[engines]' argument, got '{section_args[0]}'")
engine_mode = section_args[0]
if engine_mode in self.engines:
if engine_mode is None:
self.error(f"Already defined engine block")
else:
self.error(f"Already defined engine block for mode '{engine_mode}'")
else:
self.engines[engine_mode] = list()
continue
if section == "setup":
self.error(f"sby file syntax error: the '[setup]' section is not yet supported")
mode = "setup"
if len(self.setup) != 0:
self.error(f"sby file syntax error: '[setup]' section already defined")
if args is not None:
self.error(f"sby file syntax error: '[setup]' section does not accept any arguments, got '{args}'")
continue
# [stage <NAME> (PARENTS,...)]
if section == "stage":
self.error(f"sby file syntax error: the '[stage]' section is not yet supported")
mode = "stage"
if args is None:
self.error(f"sby file syntax error: '[stage]' section expects arguments, got none")
section_args = args.strip().split(maxsplit = 1)
if len(section_args) == 1:
parents = None
else:
parents = list(map(lambda a: a.strip(), section_args[1].split(',')))
stage_name = section_args[0]
if stage_name in self.stage:
self.error(f"stage '{stage_name}' already defined")
self.stage[stage_name] = {
'parents': parents
}
continue
if section == "script":
mode = "script"
if len(self.script) != 0:
self.error(f"sby file syntax error: '[script]' section already defined")
if args is not None:
self.error(f"sby file syntax error: '[script]' section does not accept any arguments. got {args}")
continue
if section == "autotune":
mode = "autotune"
if self.autotune_config:
self.error(f"sby file syntax error: '[autotune]' section already defined")
import sby_autotune
self.autotune_config = sby_autotune.SbyAutotuneConfig()
continue
if section == "file":
mode = "file"
if args is None:
self.error(f"sby file syntax error: '[file]' section expects a file name argument")
section_args = args.split()
if len(section_args) > 1:
self.error(f"sby file syntax error: '[file]' section expects exactly one file name argument, got {len(section_args)}")
current_verbatim_file = section_args[0]
if current_verbatim_file in self.verbatim_files:
self.error(f"duplicate file: {current_verbatim_file}")
self.verbatim_files[current_verbatim_file] = list()
continue
if section == "files":
mode = "files"
if args is not None:
self.error(f"sby file syntax error: '[files]' section does not accept any arguments. got {args}")
continue
self.error(f"sby file syntax error: unexpected section '{section}', expected one of 'options, engines, script, autotune, file, files'")
if mode == "options":
entries = line.strip().split(maxsplit = 1)
if len(entries) != 2:
self.error(f"sby file syntax error: '[options]' section entry does not have an argument '{line}'")
self.options[entries[0]] = entries[1]
continue
if mode == "autotune":
self.autotune_config.config_line(self, line)
continue
if mode == "engines":
args = line.strip().split()
self.engines[engine_mode].append(args)
continue
if mode == "setup":
_valid_options = (
"cutpoint", "disable", "enable", "assume", "define"
)
args = line.strip().split(maxsplit = 1)
if len(args) < 2:
self.error(f"sby file syntax error: entry in '[setup]' must have an argument, got '{' '.join(args)}'")
if args[0] not in _valid_options:
self.error(f"sby file syntax error: expected one of '{', '.join(_valid_options)}' in '[setup]' section, got '{args[0]}'")
else:
opt_key = args[0]
opt_args = args[1].strip().split()
if opt_key == 'define':
if 'define' not in self.setup:
self.setup['define'] = {}
if len(opt_args) != 2:
self.error(f"sby file syntax error: 'define' statement in '[setup]' section takes exactly 2 arguments, got '{' '.join(opt_args)}'")
if opt_args[0][0] != '@':
self.error(f"sby file syntax error: 'define' statement in '[setup]' section expects an '@' prefixed name as the first parameter, got '{opt_args[0]}'")
name = opt_args[0][1:]
self.setup['define'][name] = opt_args[2:]
else:
self.setup[opt_key] = opt_args[1:]
continue
if mode == "stage":
_valid_options = (
"mode", "depth", "timeout", "expect", "engine",
"cutpoint", "enable", "disable", "assume", "skip",
"check", "prove", "abstract", "setsel"
)
args = line.strip().split(maxsplit = 1)
if args is None:
self.error(f"sby file syntax error: unknown key in '[stage]' section")
if len(args) < 2:
self.error(f"sby file syntax error: entry in '[stage]' must have an argument, got {' '.join(args)}")
if args[0] not in _valid_options:
self.error(f"sby file syntax error: expected one of '{', '.join(map(repr, _valid_options))}' in '[stage]' section, got '{args[0]}'")
else:
opt_key = args[0]
opt_args = args[1].strip().split()
if opt_key == 'setsel':
if len(opt_args) != 2:
self.error(f"sby file syntax error: 'setsel' statement in '[stage]' section takes exactly 2 arguments, got '{' '.join(opt_args)}'")
if opt_args[0][0] != '@':
self.error(f"sby file syntax error: 'setsel' statement in '[stage]' section expects an '@' prefixed name as the first parameter, got '{opt_args[0]}'")
name = opt_args[0][1:]
if stage_name not in self.stage:
self.stage[stage_name] = dict()
self.stage[stage_name][opt_key] = {
'name': name, 'pattern': opt_args[2:]
}
else:
if stage_name not in self.stage:
self.stage[stage_name] = dict()
self.stage[stage_name][opt_key] = opt_args[1:]
continue
if mode == "script":
self.script.append(line)
continue
if mode == "files":
entries = line.split()
if len(entries) < 1 or len(entries) > 2:
self.error(f"sby file syntax error: '[files]' section entry expects up to 2 arguments, {len(entries)} specified")
if len(entries) == 1:
self.files[os.path.basename(entries[0])] = entries[0]
elif len(entries) == 2:
self.files[entries[0]] = entries[1]
continue
if mode == "file":
self.verbatim_files[current_verbatim_file].append(raw_line)
continue
self.error(f"sby file syntax error: In an incomprehensible mode '{mode}'")
if len(self.stage.keys()) == 0:
self.stage['default'] = { 'enable': '*' }
def error(self, logmessage):
raise SbyAbort(logmessage)
class SbyTaskloop:
def __init__(self, jobclient=None):
self.procs_pending = []
self.procs_running = []
self.tasks = []
self.poll_now = False
self.jobclient = jobclient
def run(self):
for proc in self.procs_pending:
proc.poll()
waiting_for_jobslots = False
if self.jobclient:
waiting_for_jobslots = self.jobclient.has_pending_leases()
while self.procs_running or waiting_for_jobslots or self.poll_now:
fds = []
if self.jobclient:
fds.extend(self.jobclient.poll_fds())
for proc in self.procs_running:
if proc.running:
fds.append(proc.p.stdout)
if not self.poll_now:
if os.name == "posix":
try:
select(fds, [], [], 1.0) == ([], [], [])
except InterruptedError:
pass
else:
sleep(0.1)
self.poll_now = False
if self.jobclient:
self.jobclient.poll()
self.procs_waiting = []
for proc in self.procs_running:
proc.poll()
for proc in self.procs_pending:
proc.poll()
if self.jobclient:
waiting_for_jobslots = self.jobclient.has_pending_leases()
tasks = self.tasks
self.tasks = []
for task in tasks:
task.check_timeout()
if task.procs_pending or task.procs_running:
self.tasks.append(task)
else:
task.exit_callback()
for task in self.tasks:
task.exit_callback()
@dataclass
class SbySummaryEvent:
engine_idx: int
trace: Optional[str] = field(default=None)
path: Optional[str] = field(default=None)
hdlname: Optional[str] = field(default=None)
type: Optional[str] = field(default=None)
src: Optional[str] = field(default=None)
step: Optional[int] = field(default=None)
prop: Optional[SbyProperty] = field(default=None)
engine_case: Optional[str] = field(default=None)
@property
def engine(self):
return f"engine_{self.engine_idx}"
@dataclass
class SbyTraceSummary:
trace: str
path: Optional[str] = field(default=None)
engine_case: Optional[str] = field(default=None)
events: dict = field(default_factory=lambda: defaultdict(lambda: defaultdict(list)))
@property
def kind(self):
if '$assert' in self.events:
kind = 'counterexample trace'
elif '$cover' in self.events:
kind = 'cover trace'
else:
kind = 'trace'
return kind
@dataclass
class SbyEngineSummary:
engine_idx: int
traces: dict = field(default_factory=dict)
status: Optional[str] = field(default=None)
unreached_covers: Optional[list] = field(default=None)
@property
def engine(self):
return f"engine_{self.engine_idx}"
class SbySummary:
def __init__(self, task):
self.task = task
self.timing = []
self.lines = []
self.engine_summaries = {}
self.traces = defaultdict(dict)
self.engine_status = {}
self.unreached_covers = None
def append(self, line):
self.lines.append(line)
def extend(self, lines):
self.lines.extend(lines)
def engine_summary(self, engine_idx):
if engine_idx not in self.engine_summaries:
self.engine_summaries[engine_idx] = SbyEngineSummary(engine_idx)
return self.engine_summaries[engine_idx]
def add_event(self, *args, update_status=True, **kwargs):
event = SbySummaryEvent(*args, **kwargs)
engine = self.engine_summary(event.engine_idx)
if update_status:
status_metadata = dict(source="summary_event", engine=engine.engine)
if event.prop:
if event.type == "$assert":
event.prop.status = "FAIL"
if event.path:
event.prop.tracefiles.append(event.path)
if update_status:
self.task.status_db.add_task_property_data(
event.prop,
"trace",
data=dict(path=event.path, step=event.step, **status_metadata),
)
if event.prop:
if event.type == "$cover":
event.prop.status = "PASS"
if event.path:
event.prop.tracefiles.append(event.path)
if update_status:
self.task.status_db.add_task_property_data(
event.prop,
"trace",
data=dict(path=event.path, step=event.step, **status_metadata),
)
if event.prop and update_status:
self.task.status_db.set_task_property_status(
event.prop,
data=status_metadata
)
if event.trace not in engine.traces:
engine.traces[event.trace] = SbyTraceSummary(event.trace, path=event.path, engine_case=event.engine_case)
if event.type:
by_type = engine.traces[event.trace].events[event.type]
if event.hdlname:
by_type[event.hdlname].append(event)
def set_engine_status(self, engine_idx, status, case=None):
engine_summary = self.engine_summary(engine_idx)
if case is None:
self.task.log(f"{click.style(f'engine_{engine_idx}', fg='magenta')}: Status returned by engine: {status}")
self.engine_summary(engine_idx).status = status
else:
self.task.log(f"{click.style(f'engine_{engine_idx}.{case}', fg='magenta')}: Status returned by engine for {case}: {status}")
if engine_summary.status is None:
engine_summary.status = {}
engine_summary.status[case] = status
def summarize(self, short):
omitted_excess = False
for line in self.timing:
yield line
for engine_idx, engine_cmd in self.task.engine_list():
engine_cmd = ' '.join(engine_cmd)
trace_limit = 5
prop_limit = 5
step_limit = 5
engine = self.engine_summary(engine_idx)
if isinstance(engine.status, dict):
for case, status in sorted(engine.status.items()):
yield f"{engine.engine} ({engine_cmd}) returned {status} for {case}"
elif engine.status:
yield f"{engine.engine} ({engine_cmd}) returned {engine.status}"
else:
yield f"{engine.engine} ({engine_cmd}) did not return a status"
produced_traces = False
for i, (trace_name, trace) in enumerate(sorted(engine.traces.items())):
if short and i == trace_limit:
excess = len(engine.traces) - trace_limit
omitted_excess = True
yield f"and {excess} further trace{'s' if excess != 1 else ''}"
break
case_suffix = f" [{trace.engine_case}]" if trace.engine_case else ""
if trace.path:
if short:
yield f"{trace.kind}{case_suffix}: {self.task.workdir}/{trace.path}"
else:
yield f"{trace.kind}{case_suffix}: {trace.path}"
else:
yield f"{trace.kind}{case_suffix}: <{trace.trace}>"
produced_traces = True
for event_type, events in sorted(trace.events.items()):
if event_type == '$assert':
desc = "failed assertion"
short_desc = 'assertion'
elif event_type == '$cover':
desc = "reached cover statement"
short_desc = 'cover statement'
elif event_type == '$assume':
desc = "violated assumption"
short_desc = 'assumption'
else:
continue
for j, (hdlname, same_events) in enumerate(sorted(events.items())):
if short and j == prop_limit:
excess = len(events) - prop_limit
yield f" and {excess} further {short_desc}{'s' if excess != 1 else ''}"
break
event = same_events[0]
steps = sorted(e.step for e in same_events)
if short and len(steps) > step_limit:
excess = len(steps) - step_limit
steps = [str(step) for step in steps[:step_limit]]
omitted_excess = True
steps[-1] += f" and {excess} further step{'s' if excess != 1 else ''}"
steps = f"step{'s' if len(steps) > 1 else ''} {', '.join(map(str, steps))}"
yield f" {desc} {event.hdlname} at {event.src} in {steps}"
if not produced_traces:
yield f"{engine.engine} did not produce any traces"
if self.unreached_covers is None and self.task.opt_mode == 'cover' and self.task.status != "PASS" and self.task.design:
self.unreached_covers = []
for prop in self.task.design.hierarchy:
if prop.type == prop.Type.COVER and prop.status == "UNKNOWN":
self.unreached_covers.append(prop)
if self.unreached_covers:
yield f"unreached cover statements:"
for j, prop in enumerate(self.unreached_covers):
if short and j == prop_limit:
excess = len(self.unreached_covers) - prop_limit
omitted_excess = True
yield f" and {excess} further propert{'ies' if excess != 1 else 'y'}"
break
yield f" {prop.hdlname} at {prop.location}"
for line in self.lines:
yield line
if omitted_excess:
yield f"see {self.task.workdir}/{self.task.status} for a complete summary"
def __iter__(self):
yield from self.summarize(True)
class SbyTask(SbyConfig):
def __init__(self, sbyconfig, workdir, early_logs, reusedir, taskloop=None, logfile=None):
super().__init__()
self.used_options = set()
self.models = dict()
self.workdir = workdir
self.reusedir = reusedir
self.status = "UNKNOWN"
self.total_time = 0
self.expect = list()
self.design = None
self.precise_prop_status = False
self.timeout_reached = False
self.task_local_abort = False
self.exit_callback = self.summarize
yosys_program_prefix = "" ##yosys-program-prefix##
self.exe_paths = {
"yosys": os.getenv("YOSYS", yosys_program_prefix + "yosys"),
"abc": os.getenv("ABC", yosys_program_prefix + "yosys-abc"),
"smtbmc": os.getenv("SMTBMC", yosys_program_prefix + "yosys-smtbmc"),
"witness": os.getenv("WITNESS", yosys_program_prefix + "yosys-witness"),
"suprove": os.getenv("SUPROVE", "suprove"),
"aigbmc": os.getenv("AIGBMC", "aigbmc"),
"avy": os.getenv("AVY", "avy"),
"btormc": os.getenv("BTORMC", "btormc"),
"pono": os.getenv("PONO", "pono"),
"imctk-eqy-engine": os.getenv("IMCTK_EQY_ENGINE", "imctk-eqy-engine"),
}
self.taskloop = taskloop or SbyTaskloop()
self.taskloop.tasks.append(self)
self.procs_running = []
self.procs_pending = []
self.start_clock_time = monotonic()
if os.name == "posix":
ru = resource.getrusage(resource.RUSAGE_CHILDREN)
self.start_process_time = ru.ru_utime + ru.ru_stime
self.summary = SbySummary(self)
self.logfile = logfile or open(f"{workdir}/logfile.txt", "a")
self.log_targets = [sys.stdout, self.logfile]
for line in early_logs:
click.echo(line, file=self.logfile)
if not reusedir:
with open(f"{workdir}/config.sby", "w") as f:
for line in sbyconfig:
click.echo(line, file=f)
def engine_list(self):
engines = self.engines.get(None, []) + self.engines.get(self.opt_mode, [])
return list(enumerate(engines))
def check_timeout(self):
if self.opt_timeout is not None:
total_clock_time = int(monotonic() - self.start_clock_time)
if total_clock_time > self.opt_timeout:
self.log(f"Reached TIMEOUT ({self.opt_timeout} seconds). Terminating all subprocesses.")
self.status = "TIMEOUT"
self.terminate(timeout=True)
def update_proc_pending(self, proc):
self.procs_pending.append(proc)
self.taskloop.procs_pending.append(proc)
def update_proc_running(self, proc):
self.procs_pending.remove(proc)
self.taskloop.procs_pending.remove(proc)
self.procs_running.append(proc)
self.taskloop.procs_running.append(proc)
all_procs_running.append(proc)
def update_proc_stopped(self, proc):
self.procs_running.remove(proc)
self.taskloop.procs_running.remove(proc)
all_procs_running.remove(proc)
def update_proc_canceled(self, proc):
self.procs_pending.remove(proc)
self.taskloop.procs_pending.remove(proc)
def log(self, logmessage):
tm = localtime()
line = dress_message(self.workdir, logmessage)
for target in self.log_targets:
click.echo(line, file=target)
def log_prefix(self, prefix, message=None):
prefix = f"{click.style(prefix, fg='magenta')}: "
def log(message):
self.log(f"{prefix}{message}")
if message is None:
return log
else:
log(message)
def error(self, logmessage):
tm = localtime()
self.log(click.style(f"ERROR: {logmessage}", fg="red", bold=True))
self.status = "ERROR"
if "ERROR" not in self.expect:
self.retcode = 16
else:
self.retcode = 0
self.terminate()
with open(f"{self.workdir}/{self.status}", "w") as f:
click.echo(f"ERROR: {logmessage}", file=f)
raise SbyAbort(logmessage)
def makedirs(self, path):
if self.reusedir and os.path.isdir(path):
rmtree(path, ignore_errors=True)
if not os.path.isdir(path):
os.makedirs(path)
def copy_src(self):
self.makedirs(self.workdir + "/src")
for dstfile, lines in self.verbatim_files.items():
dstfile = self.workdir + "/src/" + dstfile
self.log(f"Writing '{dstfile}'.")
with open(dstfile, "w") as f:
for line in lines:
f.write(line)
for dstfile, srcfile in self.files.items():
if dstfile.startswith("/") or dstfile.startswith("../") or ("/../" in dstfile):
self.error(f"destination filename must be a relative path without /../: {dstfile}")
dstfile = self.workdir + "/src/" + dstfile
srcfile = process_filename(srcfile)
basedir = os.path.dirname(dstfile)
if basedir != "" and not os.path.exists(basedir):
os.makedirs(basedir)
self.log(f"Copy '{os.path.abspath(srcfile)}' to '{os.path.abspath(dstfile)}'.")
if os.path.isdir(srcfile):
copytree(srcfile, dstfile, dirs_exist_ok=True)
else:
copyfile(srcfile, dstfile)
def handle_str_option(self, option_name, default_value):
if option_name in self.options:
self.__dict__["opt_" + option_name] = self.options[option_name]
self.used_options.add(option_name)
else:
self.__dict__["opt_" + option_name] = default_value
def handle_int_option(self, option_name, default_value):
if option_name in self.options:
self.__dict__["opt_" + option_name] = int(self.options[option_name])
self.used_options.add(option_name)
else:
self.__dict__["opt_" + option_name] = default_value
def handle_bool_option(self, option_name, default_value):
if option_name in self.options:
if self.options[option_name] not in ["on", "off"]:
self.error(f"Invalid value '{self.options[option_name]}' for boolean option {option_name}.")
self.__dict__["opt_" + option_name] = self.options[option_name] == "on"
self.used_options.add(option_name)
else:
self.__dict__["opt_" + option_name] = default_value
def make_model(self, model_name):