forked from zephyrproject-rtos/zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitycheck
executable file
·1668 lines (1366 loc) · 64.5 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 python
"""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 archtecture configuration file, and if possible
run the tests in the QEMU emulator.
Test cases are detected by the presence of a 'testcase.ini' file 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.ini file. The full canonical
name for each test case is <path to test case under samples/>/<block>.
Each testcase.ini block 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>
skip testcase unconditionally. This can be used for broken tests.
extra_args = <list of extra arguments>
Extra arguments to pass to Make when building or running the
test case.
build_only = <True|False>
If true, don't try to run the test under QEMU even if the
selected platform supports it.
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.
config_whitelist = <list of config options>
Config options can either be config names like CONFIG_FOO which
match if the configuration is defined to any value, or key/value
pairs like CONFIG_FOO=bar which match if it is set to a specific
value. May prepend a '!' to invert the match.
Architectures and platforms are defined in an archtecture configuration
file which are stored by default in scripts/sanity_chk/arches/. These
each define an [arch] block with the following key/value pairs:
name = <arch name>
The name of the arch. Example: x86
platforms = <list of supported platforms in order of precedence>
List of supported platforms for this arch. The ordering here
is used to select a default platform to build for that arch.
For every platform defined, there must be a corresponding block for it
in the arch configuration file. This block can be empty if there are
no special definitions for that arch. Options are:
qemu_support = <True|False> (default False)
Indicates whether binaries for this platform can run under QEMU
microkernel_support = <True|False> (default True)
Indicates whether this platform supports microkernel or just nanokernel
The set of test cases that actually run depends on directives in the
testcase and archtecture .ini file and options passed in on the command
line. If there is every 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.
Most everyday users will run with no arguments.
"""
import argparse
import os
import sys
import ConfigParser
import re
import tempfile
import subprocess
import multiprocessing
import select
import shutil
import signal
import threading
import time
import csv
import glob
os.environ["DISABLE_TRYRUN"] = "1"
if "ZEPHYR_BASE" not in os.environ:
sys.stderr.write("$ZEPHYR_BASE environment variable undefined.\n")
exit(1)
ZEPHYR_BASE = os.environ["ZEPHYR_BASE"]
VERBOSE = 0
LAST_SANITY = os.path.join(ZEPHYR_BASE, "scripts", "sanity_chk",
"last_sanity.csv")
RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "sanity_chk",
"sanity_last_release.csv")
PARALLEL = multiprocessing.cpu_count() * 2
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
# Debug Functions
def debug(what):
if VERBOSE >= 1:
print what
def error(what):
sys.stderr.write(COLOR_RED + what + COLOR_NORMAL + "\n")
def verbose(what):
if VERBOSE >= 2:
print what
def info(what):
sys.stdout.write(what + "\n")
# Utility functions
class QEMUHandler:
"""Spawns a thread to monitor QEMU output from pipes
We pass QEMU_PIPE to 'make qemu' 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.
"""
RUN_PASSED = "PROJECT EXECUTION SUCCESSFUL"
RUN_FAILED = "PROJECT EXECUTION FAILED"
@staticmethod
def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results):
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, "w")
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
c = in_fp.read(1)
if c == "":
# EOF, this shouldn't happen unless QEMU crashes
out_state = "unexpected eof"
break
line = line + c
if c != "\n":
continue
# If we get here, 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)
if line == QEMUHandler.RUN_PASSED:
out_state = "passed"
break
if line == QEMUHandler.RUN_FAILED:
out_state = "failed"
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["qemu_time"] = time.time() - start_time
verbose("QEMU complete (%s) after %f seconds" %
(out_state, metrics["qemu_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)
os.kill(pid, signal.SIGTERM)
os.unlink(fifo_in)
os.unlink(fifo_out)
def __init__(self, name, outdir, log_fn, timeout):
"""Constructor
@param name Arbitrary name of the created thread
@param outdir Working directory, shoudl be where qemu.pid gets created
by kbuild
@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
"""
# Create pipe to get QEMU's serial output
self.results = {}
self.state = "waiting"
self.lock = threading.Lock()
# We pass this to QEMU which looks for fifos with .in and .out
# suffixes.
self.fifo_fn = os.path.join(outdir, "qemu-fifo")
self.pid_fn = os.path.join(outdir, "qemu.pid")
if os.path.exists(self.pid_fn):
os.unlink(self.pid_fn)
self.log_fn = log_fn
self.thread = threading.Thread(name=name, target=QEMUHandler._thread,
args=(self, timeout, outdir, self.log_fn,
self.fifo_fn, self.pid_fn,
self.results))
self.thread.daemon = True
verbose("Spawning QEMU process for %s" % name)
self.thread.start()
def set_state(self, state, metrics):
self.lock.acquire()
self.state = state
self.metrics = metrics
self.lock.release()
def get_state(self):
self.lock.acquire()
ret = (self.state, self.metrics)
self.lock.release()
return ret
def get_fifo(self):
return self.fifo_fn
class SizeCalculator:
alloc_sections = ["bss", "noinit"]
rw_sections = ["datas", "initlevel", "_k_mem_map_ptr", "_k_pipe_ptr",
"_k_task_ptr", "_k_task_list", "initlevel", "_k_event_list"]
# These get copied into RAM only on non-XIP
ro_sections = ["text", "ctors", "rodata", "devconfig"]
def __init__(self, filename):
"""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 != "\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)
self.is_xip = (len(is_xip_output) != 0)
self.filename = filename
self.sections = []
self.rom_size = 0
self.ram_size = 0
self.mismatches = []
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 unrecogized section names
"""
slist = []
for v in self.sections:
if not v["recognized"]:
slist.append(v["name"])
return slist
def mismatched_sections(self):
"""Get a list of sections in the binary whose LMA and VMA offsets
from the previous section aren't proportional. This leads to issues
on XIP systems as they aren't correctly copied in to RAM
"""
slist = []
for v in self.sections:
if v["lma_off"] != v["vma_off"]:
slist.append((v["name"], v["lma_off"], v["vma_off"]))
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).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"
recognized = False
lma_off = 0
vma_off = 0
# Look for different section padding for LMA and VMA, if present
# this really messes up XIP systems as __csSet() copies all of
# them off flash into RAM as a single large block of memory
if self.is_xip and len(self.sections) > 0:
p = self.sections[-1]
if stype == "rw" and p["type"] == "rw":
lma_off = load_addr - p["load_addr"]
vma_off = virt_addr - p["virt_addr"]
self.sections.append({"name" : name, "load_addr" : load_addr,
"size" : size, "virt_addr" : virt_addr,
"type" : stype, "recognized" : recognized,
"lma_off" : lma_off, "vma_off" : vma_off})
class MakeGoal:
"""Metadata class representing one of the sub-makes called by MakeGenerator
MakeGenerator returns a dictionary of these which can then be associdated
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, qemu, make_log, build_log, run_log,
qemu_log):
self.name = name
self.text = text
self.qemu = qemu
self.make_log = make_log
self.build_log = build_log
self.run_log = run_log
self.qemu_log = qemu_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 qemu", qemu probably failed to start
return self.run_log
elif self.make_state == "finished":
# QEMU finished, but timed out or otherwise wasn't successful
return self.qemu_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
\t$(MAKE) -C {directory} O={outdir} V={verb} EXTRA_CFLAGS=-Werror EXTRA_ASMFLAGS=-Wa,--fatal-warnings EXTRA_LFLAGS=--fatal-warnings {args} >{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):
"""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")
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):
verb = "1" if VERBOSE else "0"
args = " ".join(args)
return MakeGenerator.MAKE_RULE_TMPL.format(phase=phase, goal=name,
outdir=outdir,
directory=workdir, verb=verb,
args=args, logfile=logfile)
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_build_goal(self, name, directory, outdir, 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
Kbuild via -O=<path>
@param args Extra command line arguments to pass to 'make', typically
environment variables or specific Make goals
"""
self._add_goal(outdir)
build_logfile = os.path.join(outdir, "build.log")
text = (self._get_rule_header(name) +
self._get_sub_make(name, "building", directory,
outdir, build_logfile, args) +
self._get_rule_footer(name))
self.goals[name] = MakeGoal(name, text, None, self.logfile, build_logfile,
None, None)
def add_qemu_goal(self, name, directory, outdir, args, timeout=30):
"""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 command line arguments to pass to 'make', typically
environment variables. Do not pass specific Make goals here.
@param timeout Maximum length of time QEMU session should be allowed
to run before automatically killing it. Default is 30 seconds.
"""
self._add_goal(outdir)
build_logfile = os.path.join(outdir, "build.log")
run_logfile = os.path.join(outdir, "run.log")
qemu_logfile = os.path.join(outdir, "qemu.log")
q = QEMUHandler(name, outdir, qemu_logfile, timeout)
args.append("QEMU_PIPE=%s" % q.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 + ["qemu"]) +
self._get_rule_footer(name))
self.goals[name] = MakeGoal(name, text, q, self.logfile, build_logfile,
run_logfile, qemu_logfile)
def add_test_instance(self, ti, build_only=False):
"""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[:]
args.extend(["ARCH=%s" % ti.platform.arch.name,
"PLATFORM_CONFIG=%s" % ti.platform.name])
if ti.platform.qemu_support and not ti.build_only and not build_only:
self.add_qemu_goal(ti.name, ti.test.code_location, ti.outdir,
args, ti.test.timeout)
else:
self.add_build_goal(ti.name, ti.test.code_location, ti.outdir, args)
def execute(self, callback_fn=None, context=None):
"""Execute all the registered build goals
@param callback_fn If not None, a callback function will be called
as individual goals transition between states. This function
should accept two parameters: a string state and an arbitrary
context object, supplied here
@param context Context object to pass to the callback function.
Type and semantics are specific to that callback function.
@return A dictionary mapping goal names to final status.
"""
with open(self.makefile, "w") as tf, \
open(os.devnull, "wb") as devnull, \
open(self.logfile, "w") as make_log:
# Create our dynamic Makefile and execute it.
# Watch stderr output which is where we will keep
# track of build state
for name, goal in self.goals.iteritems():
tf.write(goal.text)
tf.write("all: %s\n" % (" ".join(self.goals.keys())))
tf.flush()
# os.environ["CC"] = "ccache gcc" FIXME doesn't work
cmd = ["make", "-k", "-j", str(PARALLEL), "-f", tf.name, "all"]
p = subprocess.Popen(cmd, stderr=subprocess.PIPE,
stdout=devnull)
for line in iter(p.stderr.readline, b''):
make_log.write(line)
verbose("MAKE: " + repr(line.strip()))
m = MakeGenerator.re_make.match(line)
if not m:
continue
state, name, error = m.groups()
if error:
goal = self.goals[error]
else:
goal = self.goals[name]
goal.make_state = state
if error:
goal.fail("build_error")
else:
if state == "finished":
if goal.qemu:
thread_status, metrics = goal.qemu.get_state()
goal.metrics.update(metrics)
if thread_status == "passed":
goal.success()
else:
goal.fail(thread_status)
else:
goal.success()
if callback_fn:
callback_fn(context, self.goals, goal)
p.wait()
return self.goals
# "list" - List of strings
# "list:<type>" - List of <type>
# "set" - Set of unordered, unique strings
# "set:<type>" - Set of <type>
# "float" - Floating point
# "int" - Integer
# "bool" - Boolean
# "str" - String
# XXX Be sure to update __doc__ if you change any of this!!
arch_valid_keys = {"name" : {"type" : "str", "required" : True},
"platforms" : {"type" : "list", "required" : True}}
platform_valid_keys = {"qemu_support" : {"type" : "bool", "default" : False},
"microkernel_support" : {"type" : "bool",
"default" : True}}
testcase_valid_keys = {"tags" : {"type" : "set", "required" : True},
"extra_args" : {"type" : "list"},
"build_only" : {"type" : "bool", "default" : False},
"skip" : {"type" : "bool", "default" : False},
"timeout" : {"type" : "int", "default" : 60},
"arch_whitelist" : {"type" : "set"},
"arch_exclude" : {"type" : "set"},
"platform_exclude" : {"type" : "set"},
"platform_whitelist" : {"type" : "set"},
"config_whitelist" : {"type" : "set"}}
class SanityConfigParser:
"""Class to read architecture and test case .ini files with semantic checking
"""
def __init__(self, filename):
"""Instantiate a new SanityConfigParser object
@param filename Source .ini file to read
"""
cp = ConfigParser.SafeConfigParser()
cp.readfp(open(filename))
self.filename = filename
self.cp = cp
def _cast_value(self, value, typestr):
v = value.strip()
if typestr == "str":
return v
elif typestr == "float":
return float(v)
elif typestr == "int":
return int(v)
elif typestr == "bool":
v = v.lower()
if v == "true" or v == "1":
return True
elif v == "" or v == "false" or v == "0":
return False
raise ConfigurationError(self.filename,
"bad value for boolean: '%s'" % value)
elif typestr.startswith("list"):
vs = v.split()
if len(typestr) > 4 and typestr[4] == ":":
return [self._cast_value(vsi, typestr[5:]) for vsi in vs]
else:
return vs
elif typestr.startswith("set"):
vs = v.split()
if len(typestr) > 3 and typestr[3] == ":":
return set([self._cast_value(vsi, typestr[4:]) for vsi in vs])
else:
return set(vs)
else:
raise ConfigurationError(self.filename, "unknown type '%s'" % value)
def sections(self):
"""Get the set of sections within the .ini file
@return a list of string section names"""
return self.cp.sections()
def get_section(self, section, valid_keys):
"""Get a dictionary representing the keys/values within a section
@param section The section in the .ini file to retrieve data from
@param valid_keys A dictionary representing the intended semantics
for this section. Each key in this dictionary is a key that could
be specified, if a key is given in the .ini file which isn't in
here, it will generate an error. Each value in this dictionary
is another dictionary containing metadata:
"default" - Default value if not given
"type" - Data type to convert the text value to. Simple types
supported are "str", "float", "int", "bool" which will get
converted to respective Python data types. "set" and "list"
may also be specified which will split the value by
whitespace (but keep the elements as strings). finally,
"list:<type>" and "set:<type>" may be given which will
perform a type conversion after splitting the value up.
"required" - If true, raise an error if not defined. If false
and "default" isn't specified, a type conversion will be
done on an empty string
@return A dictionary containing the section key-value pairs with
type conversion and default values filled in per valid_keys
"""
d = {}
cp = self.cp
if not cp.has_section(section):
raise ConfigurationError(self.filename, "Missing section '%s'" % section)
for k, v in cp.items(section):
if k not in valid_keys:
raise ConfigurationError(self.filename,
"Unknown config key '%s' in defintiion for '%s'"
% (k, section))
d[k] = v
for k, kinfo in valid_keys.iteritems():
if k not in d:
if "required" in kinfo:
required = kinfo["required"]
else:
required = False
if required:
raise ConfigurationError(self.filename,
"missing required value for '%s' in section '%s'"
% (k, section))
else:
if "default" in kinfo:
default = kinfo["default"]
else:
default = self._cast_value("", kinfo["type"])
d[k] = default
else:
try:
d[k] = self._cast_value(d[k], kinfo["type"])
except ValueError, ve:
raise ConfigurationError(self.filename,
"bad %s value '%s' for key '%s' in section '%s'"
% (kinfo["type"], d[k], k, section))
return d
class Platform:
"""Class representing metadata for a particular platform
Maps directly to PLATFORM_CONFIG when building"""
def __init__(self, arch, name, plat_dict):
"""Constructor.
@param arch Architecture object for this platform
@param name String name for this platform, same as PLATFORM_CONFIG
@param plat_dict SanityConfigParser output on the relevant section
in the architecture configuration file which has lots of metadata.
See the Architecture class.
"""
self.name = name
self.qemu_support = plat_dict["qemu_support"]
self.microkernel_support = plat_dict["microkernel_support"]
self.arch = arch
# Gets populated in a separate step
self.defconfig = {"micro" : None, "nano" : None}
pass
def set_defconfig(self, ktype, defconfig):
"""Set defconfig information for a particular kernel type.
We do this in another step because all the defconfigs are generated
at once from a sub-make, see TestSuite constructor
@param ktype Kernel type, either "micro" or "nano"
@param defconfig Dictionary containing defconfig information
"""
self.defconfig[ktype] = defconfig
def get_defconfig(self, ktype):
"""Return a dictionary representing the key/value pairs expressed
in the kernel defconfig used for this arch/platform. Used to identify
platform features.
@param ktype Kernel type, either "micro" or "nano"
@return dictionary corresponding to the defconfig contents. unset
values will not be defined
"""
if ktype == "micro" and not self.microkernel_support:
raise SanityRuntimeError("Invalid kernel type queried")
return self.defconfig[ktype]
def __repr__(self):
return "<%s on %s>" % (self.name, self.arch.name)
class Architecture:
"""Class representing metadata for a particular architecture
"""
def __init__(self, cfile):
"""Architecture constructor
@param cfile Path to Architecture configuration file, which gives
info about the arch and all the platforms for it
"""
cp = SanityConfigParser(cfile)
self.platforms = []
arch = cp.get_section("arch", arch_valid_keys)
self.name = arch["name"]
for plat_name in arch["platforms"]:
verbose("Platform: %s" % plat_name)
plat_dict = cp.get_section(plat_name, platform_valid_keys)
self.platforms.append(Platform(self, plat_name, plat_dict))
def __repr__(self):
return "<arch %s>" % self.name
class TestCase:
"""Class representing a test application
"""
makefile_re = re.compile("\s*KERNEL_TYPE\s*[?=]+\s*(micro|nano)\s*")
def __init__(self, testcase_root, workdir, name, tc_dict):
"""TestCase constructor.
This gets called by TestSuite as it finds and reads testcase.ini files.
Multiple TestCase instances may be generated from a single testcase.ini,
each one corresponds to a section within that file.
Reads the Makefile inside the testcase directory to figure out the
kernel type for purposes of configuration filtering
We need to have a unique name for every single test case. Since
a testcase.ini can define multiple tests, the canonical name for
the test case is <workdir>/<name>.
@param testcase_root Absolute path to the root directory where
all the test cases live
@param workdir Relative path to the project directory for this
test application from the test_case root.
@param name Name of this test case, corresponding to the section name
in the test case configuration file. For many test cases that just
define one test, can be anything and is usually "test". This is
really only used to distinguish between different cases when
the testcase.ini defines multiple tests
@param tc_dict Dictionary with section values for this test case
from the testcase.ini file
"""
self.code_location = os.path.join(testcase_root, workdir)
self.tags = tc_dict["tags"]
self.extra_args = tc_dict["extra_args"]
self.arch_whitelist = tc_dict["arch_whitelist"]
self.arch_exclude = tc_dict["arch_exclude"]
self.skip = tc_dict["skip"]
self.platform_exclude = tc_dict["platform_exclude"]
self.platform_whitelist = tc_dict["platform_whitelist"]
self.config_whitelist = tc_dict["config_whitelist"]
self.timeout = tc_dict["timeout"]
self.build_only = tc_dict["build_only"]
self.path = os.path.join(workdir, name)
self.name = self.path # for now
self.ktype = None
self.defconfig = {}
with open(os.path.join(testcase_root, workdir, "Makefile")) as makefile:
for line in makefile.readlines():
m = TestCase.makefile_re.match(line)
if m:
self.ktype = m.group(1)
break
if not self.ktype:
raise ConfigurationError(os.path.join(workdir, "Makefile"),
"KERNEL_TYPE not found")
def __repr__(self):
return self.name
class TestInstance:
"""Class representing the execution of a particular TestCase on a platform
@param test The TestCase object we want to build/execute
@param platform Platform object that we want to build and run against
@param base_outdir Base directory for all test results. The actual
out directory used is <outdir>/<platform>/<test case name>
"""
def __init__(self, test, platform, base_outdir, build_only=False):
self.test = test
self.platform = platform
self.name = os.path.join(platform.name, test.path)
self.outdir = os.path.join(base_outdir, platform.name, test.path)