forked from zephyrproject-rtos/zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitycheck
executable file
·2538 lines (2096 loc) · 93.8 KB
/
sanitycheck
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
#!/usr/bin/env python3
# vim: set syntax=python ts=4 :
"""Zephyr Sanity Tests
This script scans for the set of unit test applications in the git
repository and attempts to execute them. By default, it tries to
build each test case on one platform per architecture, using a precedence
list defined in an architecture configuration file, and if possible
run the tests in the QEMU emulator.
Test cases are detected by the presence of a 'testcase.yaml' or a sample.yaml
files in the application's project directory. This file may contain one or more
blocks, each identifying a test scenario. The title of the block is a name for
the test case, which only needs to be unique for the test cases specified in
that testcase meta-data. The full canonical name for each test case is <path to
test case>/<block>.
Each test block in the testcase meta data can define the following key/value
pairs:
tags: <list of tags> (required)
A set of string tags for the testcase. Usually pertains to
functional domains but can be anything. Command line invocations
of this script can filter the set of tests to run based on tag.
skip: <True|False> (default False)
skip testcase unconditionally. This can be used for broken tests.
slow: <True|False> (default False)
Don't run this test case unless --enable-slow was passed in on the
command line. Intended for time-consuming test cases that are only
run under certain circumstances, like daily builds. These test cases
are still compiled.
extra_args: <list of extra arguments>
Extra cache entries to pass to CMake when building or running the
test case.
extra_configs: <list of extra configurations>
Extra configuration options to be merged with a master prj.conf
when building or running the test case.
build_only: <True|False> (default False)
If true, don't try to run the test under QEMU even if the
selected platform supports it.
build_on_all: <True|False> (default False)
If true, attempt to build test on all available platforms.
depends_on: <list of features>
A board or platform can announce what features it supports, this option
will enable the test only those platforms that provide this feature.
min_ram: <integer>
minimum amount of RAM needed for this test to build and run. This is
compared with information provided by the board metadata.
min_flash: <integer>
minimum amount of ROM needed for this test to build and run. This is
compared with information provided by the board metadata.
timeout: <number of seconds>
Length of time to run test in QEMU before automatically killing it.
Default to 60 seconds.
arch_whitelist: <list of arches, such as x86, arm, arc>
Set of architectures that this test case should only be run for.
arch_exclude: <list of arches, such as x86, arm, arc>
Set of architectures that this test case should not run on.
platform_whitelist: <list of platforms>
Set of platforms that this test case should only be run for.
platform_exclude: <list of platforms>
Set of platforms that this test case should not run on.
extra_sections: <list of extra binary sections>
When computing sizes, sanitycheck will report errors if it finds
extra, unexpected sections in the Zephyr binary unless they are named
here. They will not be included in the size calculation.
filter: <expression>
Filter whether the testcase should be run by evaluating an expression
against an environment containing the following values:
{ ARCH : <architecture>,
PLATFORM : <platform>,
<all CONFIG_* key/value pairs in the test's generated defconfig>,
*<env>: any environment variable available
}
The grammar for the expression language is as follows:
expression ::= expression "and" expression
| expression "or" expression
| "not" expression
| "(" expression ")"
| symbol "==" constant
| symbol "!=" constant
| symbol "<" number
| symbol ">" number
| symbol ">=" number
| symbol "<=" number
| symbol "in" list
| symbol ":" string
| symbol
list ::= "[" list_contents "]"
list_contents ::= constant
| list_contents "," constant
constant ::= number
| string
For the case where expression ::= symbol, it evaluates to true
if the symbol is defined to a non-empty string.
Operator precedence, starting from lowest to highest:
or (left associative)
and (left associative)
not (right associative)
all comparison operators (non-associative)
arch_whitelist, arch_exclude, platform_whitelist, platform_exclude
are all syntactic sugar for these expressions. For instance
arch_exclude = x86 arc
Is the same as:
filter = not ARCH in ["x86", "arc"]
The ':' operator compiles the string argument as a regular expression,
and then returns a true value only if the symbol's value in the environment
matches. For example, if CONFIG_SOC="quark_se" then
filter = CONFIG_SOC : "quark.*"
Would match it.
The set of test cases that actually run depends on directives in the testcase
filed and options passed in on the command line. If there is any confusion,
running with -v or --discard-report can help show why particular test cases
were skipped.
Metrics (such as pass/fail state and binary size) for the last code
release are stored in scripts/sanity_chk/sanity_last_release.csv.
To update this, pass the --all --release options.
To load arguments from a file, write '+' before the file name, e.g.,
+file_name. File content must be one or more valid arguments separated by
line break instead of white spaces.
Most everyday users will run with no arguments.
"""
import argparse
import os
import sys
import re
import subprocess
import multiprocessing
import select
import shutil
import signal
import threading
import time
import csv
import glob
import concurrent
import concurrent.futures
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape
from collections import OrderedDict
from itertools import islice
from functools import cmp_to_key
import logging
from sanity_chk import scl
from sanity_chk import expr_parser
log_format = "%(levelname)s %(name)s::%(module)s.%(funcName)s():%(lineno)d: %(message)s"
logging.basicConfig(format=log_format, level=30)
if "ZEPHYR_BASE" not in os.environ:
sys.stderr.write("$ZEPHYR_BASE environment variable undefined.\n")
exit(1)
ZEPHYR_BASE = os.environ["ZEPHYR_BASE"]
sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/"))
VERBOSE = 0
LAST_SANITY = os.path.join(ZEPHYR_BASE, "scripts", "sanity_chk",
"last_sanity.csv")
LAST_SANITY_XUNIT = os.path.join(ZEPHYR_BASE, "scripts", "sanity_chk",
"last_sanity.xml")
RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "sanity_chk",
"sanity_last_release.csv")
CPU_COUNTS = multiprocessing.cpu_count()
if os.isatty(sys.stdout.fileno()):
TERMINAL = True
COLOR_NORMAL = '\033[0m'
COLOR_RED = '\033[91m'
COLOR_GREEN = '\033[92m'
COLOR_YELLOW = '\033[93m'
else:
TERMINAL = False
COLOR_NORMAL = ""
COLOR_RED = ""
COLOR_GREEN = ""
COLOR_YELLOW = ""
class SanityCheckException(Exception):
pass
class SanityRuntimeError(SanityCheckException):
pass
class ConfigurationError(SanityCheckException):
def __init__(self, cfile, message):
self.cfile = cfile
self.message = message
def __str__(self):
return repr(self.cfile + ": " + self.message)
class MakeError(SanityCheckException):
pass
class BuildError(MakeError):
pass
class ExecutionError(MakeError):
pass
log_file = None
# Debug Functions
def info(what):
sys.stdout.write(what + "\n")
sys.stdout.flush()
if log_file:
log_file.write(what + "\n")
log_file.flush()
def error(what):
sys.stderr.write(COLOR_RED + what + COLOR_NORMAL + "\n")
if log_file:
log_file(what + "\n")
log_file.flush()
def debug(what):
if VERBOSE >= 1:
info(what)
def verbose(what):
if VERBOSE >= 2:
info(what)
class HarnessImporter:
def __init__(self, name):
sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/sanity_chk"))
module = __import__("harness")
if name:
my_class = getattr(module, name)
else:
my_class = getattr(module, "Test")
self.instance = my_class()
class Handler:
def __init__(self, instance):
"""Constructor
@param name Arbitrary name of the created thread
@param outdir Working directory, should be where handler pid file (qemu.pid for example)
gets created by the build system
@param log_fn Absolute path to write out handler's log data
@param timeout Kill the handler process if it doesn't finish up within
the given number of seconds
"""
self.lock = threading.Lock()
self.state = "waiting"
self.metrics = {}
self.metrics["handler_time"] = 0
self.metrics["ram_size"] = 0
self.metrics["rom_size"] = 0
def set_state(self, state, metrics):
self.lock.acquire()
self.state = state
self.metrics.update(metrics)
self.lock.release()
def get_state(self):
self.lock.acquire()
ret = (self.state, self.metrics)
self.lock.release()
return ret
class NativeHandler(Handler):
def __init__(self, instance):
"""Constructor
@param instance Test Instance
"""
super().__init__(instance)
self.instance = instance
self.timeout = instance.test.timeout
self.sourcedir = instance.test.code_location
self.outdir = instance.outdir
self.run_log = os.path.join(self.outdir, "run.log")
self.handler_log = os.path.join(self.outdir, "handler.log")
self.valgrind = False
self.returncode = 0
self.set_state("running", {})
def _output_reader(self, proc, harness):
log_out_fp = open(self.handler_log, "wt")
for line in iter(proc.stdout.readline, b''):
verbose("NATIVE: {0}".format(line.decode('utf-8').rstrip()))
log_out_fp.write(line.decode('utf-8'))
log_out_fp.flush()
harness.handle(line.decode('utf-8').rstrip())
if harness.state:
proc.terminate()
break
log_out_fp.close()
def handle(self):
out_state = "failed"
harness_name = self.instance.test.harness.capitalize()
harness_import = HarnessImporter(harness_name)
harness = harness_import.instance
harness.configure(self.instance)
binary = os.path.join(self.outdir, "zephyr", "zephyr.exe")
command = [binary]
if shutil.which("valgrind") and self.valgrind:
command = ["valgrind", "--error-exitcode=2",
"--leak-check=full"] + command
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
t = threading.Thread(target=self._output_reader, args=(proc, harness, ))
t.start()
t.join(self.timeout)
if t.is_alive():
proc.terminate()
out_state = "timeout"
t.join()
proc.wait()
self.returncode = proc.returncode
if proc.returncode != 0:
out_state = "failed"
returncode = subprocess.call(["GCOV_PREFIX=" + self.outdir, "gcov", self.sourcedir, "-b", "-s", self.outdir], shell=True)
if harness.state:
self.set_state(harness.state, {})
else:
self.set_state(out_state, {})
class UnitHandler(Handler):
def __init__(self, instance):
"""Constructor
@param instance Test instance
"""
super().__init__(instance)
self.timeout = instance.test.timeout
self.sourcedir = instance.test.code_location
self.outdir = instance.outdir
self.run_log = os.path.join(self.outdir, "run.log")
self.handler_log = os.path.join(self.outdir, "handler.log")
self.returncode = 0
self.set_state("running", {})
def handle(self):
out_state = "failed"
with open(self.run_log, "wt") as rl, open(self.handler_log, "wt") as vl:
try:
binary = os.path.join(self.outdir, "testbinary")
command = [binary]
if shutil.which("valgrind"):
command = ["valgrind", "--error-exitcode=2",
"--leak-check=full"] + command
returncode = subprocess.call(command, timeout=self.timeout,
stdout=rl, stderr=vl)
self.returncode = returncode
if returncode != 0:
if self.returncode == 1:
out_state = "failed"
else:
out_state = "failed valgrind"
else:
out_state = "passed"
except subprocess.TimeoutExpired:
out_state = "timeout"
self.returncode = 1
returncode = subprocess.call(
["GCOV_PREFIX=" + self.outdir, "gcov", self.sourcedir, "-s", self.outdir], shell=True)
self.set_state(out_state, {})
class QEMUHandler(Handler):
"""Spawns a thread to monitor QEMU output from pipes
We pass QEMU_PIPE to 'make run' and monitor the pipes for output.
We need to do this as once qemu starts, it runs forever until killed.
Test cases emit special messages to the console as they run, we check
for these to collect whether the test passed or failed.
"""
@staticmethod
def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness):
fifo_in = fifo_fn + ".in"
fifo_out = fifo_fn + ".out"
# These in/out nodes are named from QEMU's perspective, not ours
if os.path.exists(fifo_in):
os.unlink(fifo_in)
os.mkfifo(fifo_in)
if os.path.exists(fifo_out):
os.unlink(fifo_out)
os.mkfifo(fifo_out)
# We don't do anything with out_fp but we need to open it for
# writing so that QEMU doesn't block, due to the way pipes work
out_fp = open(fifo_in, "wb")
# Disable internal buffering, we don't
# want read() or poll() to ever block if there is data in there
in_fp = open(fifo_out, "rb", buffering=0)
log_out_fp = open(logfile, "wt")
start_time = time.time()
timeout_time = start_time + timeout
p = select.poll()
p.register(in_fp, select.POLLIN)
metrics = {}
line = ""
while True:
this_timeout = int((timeout_time - time.time()) * 1000)
if this_timeout < 0 or not p.poll(this_timeout):
out_state = "timeout"
break
try:
c = in_fp.read(1).decode("utf-8")
except UnicodeDecodeError:
# Test is writing something weird, fail
out_state = "unexpected byte"
break
if c == "":
# EOF, this shouldn't happen unless QEMU crashes
out_state = "unexpected eof"
break
line = line + c
if c != "\n":
continue
# line contains a full line of data output from QEMU
log_out_fp.write(line)
log_out_fp.flush()
line = line.strip()
verbose("QEMU: %s" % line)
harness.handle(line)
if harness.state:
out_state = harness.state
break
# TODO: Add support for getting numerical performance data
# from test cases. Will involve extending test case reporting
# APIs. Add whatever gets reported to the metrics dictionary
line = ""
metrics["handler_time"] = time.time() - start_time
verbose("QEMU complete (%s) after %f seconds" %
(out_state, metrics["handler_time"]))
handler.set_state(out_state, metrics)
log_out_fp.close()
out_fp.close()
in_fp.close()
pid = int(open(pid_fn).read())
os.unlink(pid_fn)
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
# Oh well, as long as it's dead! User probably sent Ctrl-C
pass
os.unlink(fifo_in)
os.unlink(fifo_out)
def __init__(self, instance):
"""Constructor
@param name Arbitrary name of the created thread
@param outdir Working directory, should be where qemu.pid gets created
by the build system
@param log_fn Absolute path to write out QEMU's log data
@param timeout Kill the QEMU process if it doesn't finish up within
the given number of seconds
"""
super().__init__(instance)
outdir = instance.outdir
timeout = instance.test.timeout
name = instance.name
run_log = os.path.join(outdir, "run.log")
handler_log = os.path.join(outdir, "handler.log")
self.results = {}
# We pass this to QEMU which looks for fifos with .in and .out
# suffixes.
self.fifo_fn = os.path.join(instance.outdir, "qemu-fifo")
self.pid_fn = os.path.join(instance.outdir, "qemu.pid")
if os.path.exists(self.pid_fn):
os.unlink(self.pid_fn)
self.log_fn = handler_log
harness_import = HarnessImporter(instance.test.harness.capitalize())
harness = harness_import.instance
harness.configure(instance)
self.thread = threading.Thread(name=name, target=QEMUHandler._thread,
args=(self, timeout, outdir,
self.log_fn, self.fifo_fn,
self.pid_fn, self.results, harness))
self.thread.daemon = True
verbose("Spawning QEMU process for %s" % name)
self.thread.start()
def get_fifo(self):
return self.fifo_fn
class SizeCalculator:
alloc_sections = ["bss", "noinit", "app_bss", "app_noinit", "ccm_bss",
"ccm_noinit"]
rw_sections = ["datas", "initlevel", "_k_task_list", "_k_event_list",
"_k_memory_pool", "exceptions", "initshell",
"_static_thread_area", "_k_timer_area", "_k_work_area",
"_k_mem_slab_area", "_k_mem_pool_area",
"_k_sem_area", "_k_mutex_area", "_k_alert_area",
"_k_fifo_area", "_k_lifo_area", "_k_stack_area",
"_k_msgq_area", "_k_mbox_area", "_k_pipe_area",
"net_if", "net_if_dev", "net_stack", "net_l2_data",
"_k_queue_area", "_net_buf_pool_area", "app_datas",
"kobject_data", "mmu_tables", "app_pad", "priv_stacks",
"ccm_data"]
# These get copied into RAM only on non-XIP
ro_sections = ["text", "ctors", "init_array", "reset", "object_access",
"rodata", "devconfig", "net_l2", "vector"]
def __init__(self, filename, extra_sections):
"""Constructor
@param filename Path to the output binary
The <filename> is parsed by objdump to determine section sizes
"""
# Make sure this is an ELF binary
with open(filename, "rb") as f:
magic = f.read(4)
if (magic != b'\x7fELF'):
raise SanityRuntimeError("%s is not an ELF binary" % filename)
# Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK.
# GREP can not be used as it returns an error if the symbol is not
# found.
is_xip_command = "nm " + filename + \
" | awk '/CONFIG_XIP/ { print $3 }'"
is_xip_output = subprocess.check_output(
is_xip_command, shell=True, stderr=subprocess.STDOUT).decode(
"utf-8").strip()
if is_xip_output.endswith("no symbols"):
raise SanityRuntimeError("%s has no symbol information" % filename)
self.is_xip = (len(is_xip_output) != 0)
self.filename = filename
self.sections = []
self.rom_size = 0
self.ram_size = 0
self.extra_sections = extra_sections
self._calculate_sizes()
def get_ram_size(self):
"""Get the amount of RAM the application will use up on the device
@return amount of RAM, in bytes
"""
return self.ram_size
def get_rom_size(self):
"""Get the size of the data that this application uses on device's flash
@return amount of ROM, in bytes
"""
return self.rom_size
def unrecognized_sections(self):
"""Get a list of sections inside the binary that weren't recognized
@return list of unrecognized section names
"""
slist = []
for v in self.sections:
if not v["recognized"]:
slist.append(v["name"])
return slist
def _calculate_sizes(self):
""" Calculate RAM and ROM usage by section """
objdump_command = "objdump -h " + self.filename
objdump_output = subprocess.check_output(
objdump_command, shell=True).decode("utf-8").splitlines()
for line in objdump_output:
words = line.split()
if (len(words) == 0): # Skip lines that are too short
continue
index = words[0]
if (not index[0].isdigit()): # Skip lines that do not start
continue # with a digit
name = words[1] # Skip lines with section names
if (name[0] == '.'): # starting with '.'
continue
# TODO this doesn't actually reflect the size in flash or RAM as
# it doesn't include linker-imposed padding between sections.
# It is close though.
size = int(words[2], 16)
if size == 0:
continue
load_addr = int(words[4], 16)
virt_addr = int(words[3], 16)
# Add section to memory use totals (for both non-XIP and XIP scenarios)
# Unrecognized section names are not included in the calculations.
recognized = True
if name in SizeCalculator.alloc_sections:
self.ram_size += size
stype = "alloc"
elif name in SizeCalculator.rw_sections:
self.ram_size += size
self.rom_size += size
stype = "rw"
elif name in SizeCalculator.ro_sections:
self.rom_size += size
if not self.is_xip:
self.ram_size += size
stype = "ro"
else:
stype = "unknown"
if name not in self.extra_sections:
recognized = False
self.sections.append({"name": name, "load_addr": load_addr,
"size": size, "virt_addr": virt_addr,
"type": stype, "recognized": recognized})
class MakeGoal:
"""Metadata class representing one of the sub-makes called by MakeGenerator
MakeGenerator returns a dictionary of these which can then be associated
with TestInstances to get a complete picture of what happened during a test.
MakeGenerator is used for tasks outside of building tests (such as
defconfigs) which is why MakeGoal is a separate class from TestInstance.
"""
def __init__(self, name, text, handler, make_log, build_log, run_log, handler_log):
self.name = name
self.text = text
self.handler = handler
self.make_log = make_log
self.build_log = build_log
self.run_log = run_log
self.handler_log = handler_log
self.make_state = "waiting"
self.failed = False
self.finished = False
self.reason = None
self.metrics = {}
def get_error_log(self):
if self.make_state == "waiting":
# Shouldn't ever see this; breakage in the main Makefile itself.
return self.make_log
elif self.make_state == "building":
# Failure when calling the sub-make to build the code
return self.build_log
elif self.make_state == "running":
# Failure in sub-make for "make run", qemu probably failed to start
return self.run_log
elif self.make_state == "finished":
# Execution handler finished, but timed out or otherwise wasn't successful
return self.handler_log
def fail(self, reason):
self.failed = True
self.finished = True
self.reason = reason
def success(self):
self.finished = True
def __str__(self):
if self.finished:
if self.failed:
return "[%s] failed (%s: see %s)" % (self.name, self.reason,
self.get_error_log())
else:
return "[%s] passed" % self.name
else:
return "[%s] in progress (%s)" % (self.name, self.make_state)
class MakeGenerator:
"""Generates a Makefile which just calls a bunch of sub-make sessions
In any given test suite we may need to build dozens if not hundreds of
test cases. The cleanest way to parallelize this is to just let Make
do the parallelization, sharing the jobserver among all the different
sub-make targets.
"""
GOAL_HEADER_TMPL = """.PHONY: {goal}
{goal}:
"""
MAKE_RULE_TMPL = """\t@echo sanity_test_{phase} {goal} >&2
\tcmake \\
\t\t-G"{generator}"\\
\t\t-H{directory}\\
\t\t-B{outdir}\\
\t\t-DEXTRA_CFLAGS="-Werror {cflags}"\\
\t\t-DEXTRA_AFLAGS=-Wa,--fatal-warnings\\
\t\t-DEXTRA_LDFLAGS="{ldflags}"\\
\t\t{args}\\
\t\t>{logfile} 2>&1
\t{generator_cmd} -C {outdir}\\
\t\t{verb} {make_args}\\
\t\t>>{logfile} 2>&1
"""
GOAL_FOOTER_TMPL = "\t@echo sanity_test_finished {goal} >&2\n\n"
re_make = re.compile(
"sanity_test_([A-Za-z0-9]+) (.+)|$|make[:] \*\*\* \[(.+:.+: )?(.+)\] Error.+$")
def __init__(self, base_outdir, asserts=False, deprecations=False):
"""MakeGenerator constructor
@param base_outdir Intended to be the base out directory. A make.log
file will be created here which contains the output of the
top-level Make session, as well as the dynamic control Makefile
@param verbose If true, pass V=1 to all the sub-makes which greatly
increases their verbosity
"""
self.goals = {}
if not os.path.exists(base_outdir):
os.makedirs(base_outdir)
self.logfile = os.path.join(base_outdir, "make.log")
self.makefile = os.path.join(base_outdir, "Makefile")
self.asserts = asserts
self.deprecations = deprecations
def _get_rule_header(self, name):
return MakeGenerator.GOAL_HEADER_TMPL.format(goal=name)
def _get_sub_make(self, name, phase, workdir, outdir,
logfile, args, make_args=""):
"""
@param args Arguments given to CMake
@param make_args Arguments given to the Makefile generated by CMake
"""
args = " ".join(["-D{}".format(a) for a in args])
ldflags = ""
if self.asserts:
cflags = "-DCONFIG_ASSERT=1 -D__ASSERT_ON=2"
else:
cflags = ""
if self.deprecations:
cflags = cflags + " -Wno-deprecated-declarations"
if not "native_posix" in args:
ldflags="-Wl,--fatal-warnings"
if options.ninja:
generator = "Ninja"
generator_cmd = "ninja"
verb = "-v" if VERBOSE else ""
else:
generator = "Unix Makefiles"
generator_cmd = "$(MAKE)"
verb = "VERBOSE=1" if VERBOSE else "VERBOSE=0"
return MakeGenerator.MAKE_RULE_TMPL.format(
generator=generator,
generator_cmd=generator_cmd,
phase=phase,
goal=name,
outdir=outdir,
cflags=cflags,
ldflags=ldflags,
directory=workdir,
verb=verb,
args=args,
logfile=logfile,
make_args=make_args
)
def _get_rule_footer(self, name):
return MakeGenerator.GOAL_FOOTER_TMPL.format(goal=name)
def _add_goal(self, outdir):
if not os.path.exists(outdir):
os.makedirs(outdir)
def add_instance_build_goal(self, instance, args, buildlog, make_args=""):
self.add_build_goal(instance.name, instance.test.code_location,
instance.outdir, args, buildlog, make_args)
def add_build_goal(self, name, directory, outdir,
args, buildlog, make_args=""):
"""Add a goal to invoke a Kbuild session
@param name A unique string name for this build goal. The results
dictionary returned by execute() will be keyed by this name.
@param directory Absolute path to working directory, will be passed
to make -C
@param outdir Absolute path to output directory, will be passed to
cmake via -B=<path>
@param args Extra command line arguments to pass to 'cmake', typically
environment variables or specific Make goals
"""
self._add_goal(outdir)
build_logfile = os.path.join(outdir, buildlog)
text = (
self._get_rule_header(name) +
self._get_sub_make(
name,
"building",
directory,
outdir,
build_logfile,
args,
make_args=make_args) +
self._get_rule_footer(name))
self.goals[name] = MakeGoal(
name,
text,
None,
self.logfile,
build_logfile,
None,
None)
def add_qemu_goal(self, instance, args):
"""Add a goal to build a Zephyr project and then run it under QEMU
The generated make goal invokes Make twice, the first time it will
build the default goal, and the second will invoke the 'qemu' goal.
The output of the QEMU session will be monitored, and terminated
either upon pass/fail result of the test program, or the timeout
is reached.
@param name A unique string name for this build goal. The results
dictionary returned by execute() will be keyed by this name.
@param directory Absolute path to working directory, will be passed
to make -C
@param outdir Absolute path to output directory, will be passed to
Kbuild via -O=<path>
@param args Extra cache entries to define in CMake.
@param timeout Maximum length of time QEMU session should be allowed
to run before automatically killing it. Default is 30 seconds.
"""
name = instance.name
directory = instance.test.code_location
outdir = instance.outdir
build_logfile = os.path.join(outdir, "build.log")
run_logfile = os.path.join(outdir, "run.log")
handler_logfile = os.path.join(outdir, "handler.log")
self._add_goal(outdir)
qemu_handler = QEMUHandler(instance)
args.append("QEMU_PIPE=%s" % qemu_handler.get_fifo())
text = (self._get_rule_header(name) +
self._get_sub_make(name, "building", directory,
outdir, build_logfile, args) +
self._get_sub_make(name, "running", directory,
outdir, run_logfile,
args, make_args="run") +
self._get_rule_footer(name))
self.goals[name] = MakeGoal(name, text, qemu_handler, self.logfile, build_logfile,
run_logfile, handler_logfile)
def add_unit_goal(self, instance, args, timeout=30, coverage=False):
outdir = instance.outdir
timeout = instance.test.timeout
name = instance.name
directory = instance.test.code_location
self._add_goal(outdir)
build_logfile = os.path.join(outdir, "build.log")
run_logfile = os.path.join(outdir, "run.log")
handler_logfile = os.path.join(outdir, "handler.log")
args += ["COVERAGE=1", "EXTRA_LDFLAGS=--coverage"]
# we handle running in the UnitHandler class
text = (self._get_rule_header(name) +
self._get_sub_make(name, "building", directory,
outdir, build_logfile, args) +
self._get_rule_footer(name))
unit_handler = UnitHandler(instance)
self.goals[name] = MakeGoal(name, text, unit_handler, self.logfile, build_logfile,
run_logfile, handler_logfile)
def add_native_goal(self, instance, args, coverage=False):
outdir = instance.outdir
timeout = instance.test.timeout
name = instance.name
directory = instance.test.code_location
self._add_goal(outdir)
build_logfile = os.path.join(outdir, "build.log")
run_logfile = os.path.join(outdir, "run.log")
handler_logfile = os.path.join(outdir, "handler.log")
# we handle running in the NativeHandler class
text = (self._get_rule_header(name) +
self._get_sub_make(name, "building", directory,
outdir, build_logfile, args) +
self._get_rule_footer(name))
native_handler = NativeHandler(instance)
self.goals[name] = MakeGoal(name, text, native_handler, self.logfile, build_logfile,
run_logfile, handler_logfile)
def add_test_instance(self, ti, build_only=False, enable_slow=False, coverage=False,
extra_args=[]):
"""Add a goal to build/test a TestInstance object
@param ti TestInstance object to build. The status dictionary returned
by execute() will be keyed by its .name field.
"""
args = ti.test.extra_args[:]
if len(ti.test.extra_configs) > 0:
args.append("OVERLAY_CONFIG=%s" %
os.path.join(ti.outdir, "overlay.conf"))
args.append("BOARD={}".format(ti.platform.name))