-
Notifications
You must be signed in to change notification settings - Fork 1
/
survey-scan
executable file
·4516 lines (3898 loc) · 176 KB
/
survey-scan
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
# -*- encoding: us-ascii -*-
# vim: set ai ts=4 sw=4 et:
# Copyright 2013 Zack Weinberg <[email protected]> and other contributors.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# There is NO WARRANTY.
# This script determines which subset of a large list of "common"
# header files are present on your operating system. It also probes
# for conflicts among the headers, and for those headers whose
# contents are defined by the C or POSIX standards, it checks for
# missing declarations.
#
# For detailed instructions on how to run this script, see
# doc/inventories.md.
#
# WARNING: This script is not feature complete yet; you can't actually
# take an inventory as described in inventories.md.
#
# NOTE: This script is backward compatible all the way to Python 2.0,
# and therefore uses many constructs which are considered obsolete,
# and avoids many conveniences added after that point.
import ConfigParser
import StringIO
import errno
import glob
import locale
import os
import random
import re
import stat
import string
import sys
import time
# suppress all Python warnings, since we deliberately use deprecated
# things (that were the only option in 2.0)
try:
import warnings
warnings.simplefilter("ignore")
except:
pass
# on Windows, attempt to suppress "critical error" dialog boxes
# (e.g. missing DLLs) which may pop up from subprocesses.
if sys.platform == 'win32':
try:
import ctypes
# SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX
ctypes.windll.kernel32.SetErrorMode(0x0001|0x0002|0x8000)
except:
pass
# "True" division only became available in Python 2.2. Therefore, it is a
# style violation to use bare / or // anywhere in this program other than
# via these wrappers. Note that "from __future__ import division" cannot
# be written inside a try block, and that without the "exec", the
# SyntaxError won't get caught.
try:
exec "def floordiv(n,d): return n // d"
except SyntaxError:
def floordiv(n,d): return n / d
def truediv(n,d): return float(n) / float(d)
# used out of an overabundance of caution; falling back to eval with
# no globals or locals is probably safe enough
try:
from ast import literal_eval
except ImportError:
def literal_eval(expr):
return eval(expr, {'__builtins__':{}}, {})
# It may be necessary to monkey-patch ConfigParser to accept / in an option
# name and/or : in a section name. Also test empty values (not to be confused
# with the absence of a value, i.e. no : or = at all).
def maybe_fix_ConfigParser():
p = ConfigParser.ConfigParser()
test = StringIO.StringIO("[x:y/z.w]\na.b/c.d=\n")
try:
p.readfp(test)
except ConfigParser.ParsingError:
if (not getattr(ConfigParser.ConfigParser, 'SECTCRE')
or not getattr(ConfigParser.ConfigParser, 'OPTCRE')):
raise # we don't know what to do
# this is taken verbatim from 2.7
ConfigParser.ConfigParser.SECTCRE = re.compile(
r'\[' # [
r'(?P<header>[^]]+)' # very permissive!
r'\]' # ]
)
# this is slightly modified from 2.7 to work around different
# behavior in 2.0's regular expression engine
ConfigParser.ConfigParser.OPTCRE = re.compile(
r'(?P<option>[^:=\s]+)' # very permissive!
r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
# followed by separator
# (either : or =), followed
# by any # space/tab
r'(?P<value>.*)$' # everything up to eol
)
p = ConfigParser.ConfigParser()
test.seek(0)
p.readfp(test)
maybe_fix_ConfigParser()
def group_matched(grp):
"""True if 'grp', the return value of re.MatchObject.group(),
represents a successfully matched group. At some point in the 2.x
series, match.group(N) changed from returning -1 to returning None
if the group was part of an unmatched alternative. Also reject the
empty string (this can be returned on a successful match, but is
never what we want in context)."""
return grp is not None and grp != -1 and grp != ""
_universal_readlines_re = re.compile("\r\n|\r|\n")
def universal_readlines(fname):
"""Replacement for the Python 2.3+ "universal newlines" feature in open().
Doesn't even try to use "rU" because opening a file in that mode
silently succeeds (but does not do what one wants) on older Pythons."""
f = open(fname, "rb")
s = f.read().strip()
f.close()
if s == "": return []
return _universal_readlines_re.split(s)
def named_tmpfile(prefix="tmp", suffix="txt"):
"""Create a scratch file, with a unique name, in the current directory.
Returns the name of the scratch file, which exists, but is not open.
Caller is responsible for cleaning up. 8.3 compliant if caller
provides no more than three-character prefixes and suffixes.
2.0 `tempfile` does not have NamedTemporaryFile, and doesn't have
anything useful for defining it, either. This is kinda sorta like
the code implementing 2.7's NamedTemporaryFile."""
symbols = "abcdefghijklmnopqrstuvwxyz01234567890"
tries = 0
while 1:
candidate = "".join([random.choice(symbols) for _ in (1,2,3,4,5)])
path = prefix + candidate + "." + suffix
try:
os.close(os.open(path, os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0600))
return path
except EnvironmentError, e:
if e.errno != errno.EEXIST:
raise
# The code above can generate 60,466,176 different names,
# but give up after ten thousand iterations; we don't want
# to spend hours looping if something is genuinely wrong.
tries += 1
if tries == 10000:
raise
# otherwise loop
# The textwrap module was added in Python 2.3.
# break_on_hyphens was added in 2.6 and the constructor is _not_
# forward compatible.
try:
import textwrap
try:
_diagnostic_wrapper = textwrap.TextWrapper(width=76,
subsequent_indent=" ",
break_long_words=0,
break_on_hyphens=0)
except TypeError:
_diagnostic_wrapper = textwrap.TextWrapper(width=76,
subsequent_indent=" ",
break_long_words=0)
def wrap_diagnostic(msg):
"""Line-wrap diagnostic message MSG for output to a standard 80-
column terminal. Subsequent lines of the diagnostic are
indented for clarity."""
return _diagnostic_wrapper.fill(msg)
def wrap_long_list(key, value):
"""Line-wrap the long list VALUE for output as part of an inventory.
KEY is the .ini-file key it is to be associated with."""
try:
wrapper = textwrap.TextWrapper(width=78,
initial_indent = key + " = ",
subsequent_indent = " ",
break_long_words=0,
break_on_hyphens=0)
except TypeError:
wrapper = textwrap.TextWrapper(width=78,
initial_indent = key + " = ",
subsequent_indent = " ",
break_long_words=0)
return wrapper.wrap(value)
except (ImportError, AttributeError):
def wrap_diagnostic(msg):
"""As above but using a less sophisticated paragraph-filling
algorithm. Present for 2.0 compatibility only."""
obuf = []
line = []
linelen = 0
for word in msg.split():
linelen += 1 + len(word)
if linelen > 76:
obuf.append(" ".join(line))
line = [" "]
linelen = 3 + len(word)
line.append(word)
obuf.append(" ".join(line))
return "\n".join(obuf)
def wrap_long_list(key, value):
raise NotImplementedError
# The hashlib module was added in Python 2.5.
# Older Python does not appear to provide sha256, and sha1 should be good
# enough for our purposes (detecting whether any of the configuration has
# changed since an inventory was taken, in a non-adversarial context).
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
# Process invocation helpers.
# We can't use subprocess, it's too new. We can't use os.popen*, because
# they don't report the exit code. So... os.system it is. Which means we
# have to shell-quote, which is different on Windows. It is convenient to
# express the platform-specific logic as a function which quotes *one*
# argument; it then works on both Windows and Unix to map this function
# over the argument list and join the result list with spaces.
#
# We don't use subprocess.list2cmdline for the Windows case because it only
# quotes for [the MSVC runtime's] CommandLineToArgvW(), whereas what we need
# is quoting for CommandLineToArgvW *plus* quoting for CMD.EXE, and it
# turns out that it's easier to do both steps ourselves than to requote
# what subprocess.list2cmdline returns, because we need to know the
# boundaries between arguments for both steps. Code borrowed with
# extensive modification from Py2.7's subprocess.list2cmdline. See also
# http://msdn.microsoft.com/en-us/library/17w5ykft.aspx and
# http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
if sys.platform == "win32":
def shellquote1(arg):
"""Quote one subprocess argument to survive passage through
CMD.EXE and CommandLineToArgvW (in that order)."""
# Phase 1: quote for CommandLineToArgvW. The only characters
# that require quotation are space, tab, and double quote. If
# any of the above are present, then the whole argument must
# be surrounded by double quotes, any literal double quotes
# must be escaped with backslashes, and any backslashes *which
# immediately precede a double quote* must be escaped with
# more backslashes. Note that backslash is *only* significant
# if it's part of a train of backslashes immediately followed
# by a double quote. It is technically not necessary to wrap
# arguments that contain double quotes but *not* spaces or
# tabs in more double quotes, but it is logically simpler.
if arg == '':
qarg = ['"', '"']
elif (' ' not in arg and '\t' not in arg and '"' not in arg):
qarg = [c for c in arg]
else:
qarg = ['"']
bs_buf = []
for c in arg:
if c == '\\':
# Don't know if we need to double yet.
bs_buf.append(c)
elif c == '"':
# Double backslashes.
qarg.extend(bs_buf)
qarg.extend(bs_buf)
bs_buf = []
qarg.append('\\"')
else:
# Normal char
if bs_buf:
qarg.extend(bs_buf)
bs_buf = []
qarg.append(c)
# Trailing backslashes must be doubled, since the
# close quote mark immediately follows.
qarg.extend(bs_buf)
qarg.extend(bs_buf)
qarg.append('"')
# Phase 2: quote for CMD.EXE, for which backslash is *not* a
# special character but space, tab, double quote, and several
# other punctuators are. This process is much simpler: escape
# each special character with a caret (including caret
# itself).
qqarg = []
for c in qarg:
if c in ' \t!"%&()<>^|':
qqarg.append('^')
qqarg.append(c)
return ''.join(qqarg)
else:
# not Windows; assume os.system is Bourne-shell-like
try:
# shlex.quote is the documented API for Bourne-shell quotation, but
# is only available in 3.3 and later. We try to import it anyway,
# despite that this program has no hope of running correctly under
# 3.x; who knows, maybe there will be a 2.8 that has it.
from shlex import quote as shellquote1
except (ImportError, AttributeError):
# pipes.quote is undocumented but has existed all the way back
# to 2.0. It is semantically identical to shlex.quote.
from pipes import quote as shellquote1
def list2shell(argv):
"""Given an arbitrary argument vector (including the command name)
return a string which can be passed to os.system to execute that
command as execvp() would have, i.e. all shell metacharacters are
neutralized."""
# Square brackets here required for pre-Python 2.4 compatibility.
return " ".join([shellquote1(arg) for arg in argv])
# The above quotation scheme is also used for serializing command
# lines and command line fragments into inventories, so we need to
# be able to undo it.
if sys.platform == "win32":
# The least-effort way to undo quoting for CommandLineToArgvW is to
# call CommandLineToArgvW.
import ctypes
_CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
_CommandLineToArgvW.argtypes = [ctypes.c_wchar_p,
ctypes.POINTER(ctypes.c_int)]
_CommandLineToArgvW.restype = ctypes.POINTER(ctypes.c_wchar_p)
def shell2list(cmdline):
# Phase 1: undo quoting for CMD.EXE.
buf1 = []
after_escape = 0
for c in cmdline:
if after_escape:
buf1.append(c)
after_escape = 0
else:
if c == '^':
after_escape = 1
else:
buf1.append(c)
buf1 = "".join(buf1)
if buf1.find('"') == -1:
# no second level of quoting present, so it's safe to just
# split on whitespace
return buf1.split()
# Phase 2: undo quoting for CommandLineToArgvW.
argc = ctypes.c_int(0)
argv = _CommandLineToArgvW(buf1, ctypes.byref(argc))
return [argv[i].encode("ascii") for i in range(argc.value)]
else:
# shlex.split was added in 2.3.
# The fallback definition below is not quite right (because the 'posix'
# and 'whitespace_split' options were also only added in 2.3) but the
# difference only matters in cases that shouldn't come up, we hope.
# (For instance, empty arguments will be mishandled.)
try:
from shlex import split as shell2list
except ImportError:
from shlex import shlex as _shlex
def shell2list(cmdline):
lex = _shlex(StringIO.StringIO(cmdline))
lex.commenters = ''
lex.wordchars = (string.letters + string.digits +
# all ASCII punctuation except '"`\
"!#$%&()*+,-./:;<=>?@[]^_{|}~")
result = []
while 1:
token = lex.get_token()
if token == "": break
result.append(token)
return result
#
# utility routines that aren't workarounds for old Python
#
def delete_if_exists(fname):
"""Delete FNAME; do not raise an exception if FNAME already
doesn't exist. Used to clean up files that may or may not
have been created by a compile invocation."""
if fname is None or fname == "":
return
try:
os.remove(fname)
except EnvironmentError, e:
if e.errno != errno.ENOENT:
raise
def plural(n):
"""Return the appropriate English suffix for N items.
Use like so: "%d item%s" % (n, plural(n))."""
if n == 1: return ""
return "s"
def english_boolean(s):
s = s.strip().lower()
if s == "yes" or s == "on" or s == "true" or s == "1":
return 1
if s == "no" or s == "off" or s == "false" or s == "0":
return 0
raise RuntimeError("'%s' is not recognized as true or false" % s)
def splitto(string, sep, fields):
"""Split STRING at instances of SEP into exactly FIELDS fields."""
exploded = string.split(sep, fields-1)
if len(exploded) < fields:
exploded.extend([""] * (fields - len(exploded)))
return exploded
def not_a_subset(l, m):
"""Return true if L is nonempty and not a subset of M."""
if not l: return 0
if not m: return 1
for x in l:
for y in m:
if x is y: break
else:
return 1
return 0
squishwhite_re = re.compile(r"\s+")
def squishwhite(s):
"""Remove leading and trailing whitespace from S, and collapse each
segment of internal whitespace within S to a single space."""
return squishwhite_re.sub(" ", s.strip())
def cfg_maybe_get(parser, section, option):
"""Wrapper around ConfigParser.get which returns None if either the
section or the option doesn't exist."""
try:
return parser.get(section, option, raw=1)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
return None
def cfg_maybe_options(parser, section):
"""Wrapper around ConfigParser.options which returns [] if the section
doesn't exist."""
try:
return parser.options(section)
except ConfigParser.NoSectionError:
return []
def hsortkey(h):
"""Sort key generator for sorthdr."""
segs = str(h).lower().replace("\\", "/").split("/")
key = []
for s in segs:
key.extend((1, s))
key[-2] = 0
return tuple(key)
def sorthdr(hs):
"""Sort a list of pathnames, ASCII case-insensitively.
All one-component pathnames are sorted ahead of all longer
pathnames; within a group of multicomponent pathnames with the
same leading component, all two-component pathnames are sorted
ahead of all longer pathnames; and so on, recursively."""
try:
return sorted(hs, key=hsortkey)
except NameError:
# key= and sorted() were both added in 2.4
# implement the Schwartzian Transform by hand
khs = [(hsortkey(h), h) for h in hs]
khs.sort()
return [x[1] for x in khs]
def dependency_combs_r(lo, hi, elts, work, rv):
"""Recursive worker subroutine of dependency_combs (see below)."""
if lo < hi:
if lo == 0:
nlo = 0
else:
nlo = work[lo-1] + 1
for i in xrange(nlo, len(elts)):
work[lo] = i
dependency_combs_r(lo+1, hi, elts, work, rv)
else:
rv.append([elts[work[i]] for i in xrange(hi)])
def dependency_combs(deps):
"""Given an ordered list of header files, DEPS, that may be
necessary prior to inclusion of some other header, produce a
list of all possible subsets of that list, maintaining order.
(This is not a generator because generators did not exist in
2.0. We expect we can get away with generating a list of 2^N
lists, as len(deps) is 4 in the worst case currently known.)
The list is in "banker's" order as defined in
http://applied-math.org/subset.pdf -- all 1-element subsets,
then all 2-element subsets, and so on. The algorithm is also
taken from that paper."""
rv = []
l = len(deps)
work = [None]*l
for i in xrange(l+1):
dependency_combs_r(0, i, deps, work, rv)
return rv
def subst_filename(fname, opts):
"""If any of OPTS is of the form '$.extension', replace the
dollar sign with FNAME's base name. Returns the modified
string or list."""
(base, _) = os.path.splitext(fname)
if type(opts) == type(""):
if opts.startswith("$."):
return base + opts[1:]
else:
return opts
else:
nopts = []
for opt in opts:
if opt.startswith("$."):
nopts.append(base + opt[1:])
else:
nopts.append(opt)
return nopts
_canonize_pp_output_re = re.compile(r'"cc[it][a-z0-9]{5}\.c"')
def canonize_pp_output(out):
"""Remove meaningless variation from OUT, which is preprocessing output
as generated by Compiler.invoke() (see below). Returns one giant
string rather than a list of per-line strings."""
# preallocate return vector
canon = [""]*(len(out)-1)
# The very first entry in OUT will always be the compiler invocation,
# which we don't want.
for i in range(1, len(out)):
# Remove instances of the name of the input file (which is changed for
# every invocation).
canon[i-1] = _canonize_pp_output_re.sub('"<sourcefile>"', out[i])
return "\n".join(canon)
def find_tagged_error(msg, tags):
"""Scan MSG for a error message naming one of the tags in TAGS.
This is used on the result of preprocessing source code of the form
#if condition 1
#error "tag1"
#elif condition 2
#error "tag2"
...
#endif
to extract information of various sorts from the compiler."""
for line in msg:
if line.find("error") != -1:
for name in tags:
if re.search(r'\b' + name + r'\b', line):
return name
if re.search(r'\bUNKNOWN\b', line):
return "UNKNOWN"
return "FAIL"
class NoSuchHeaderError(Exception):
"""Used in a small handful of places, where the absence of a header
means we can skip a whole bunch of tests."""
def __init__(self, header):
self.header = header
def __str__(self):
return "no such header: " + self.header
#
# Logging
#
class Logger:
"""Logger is a singleton class which owns the log file and the
terminal (to which progress reports will be written). Logger
is also responsible for adjusting the standard streams and the
environment for safe subprocess invocation, and for tracking
whether an error has occurred (i.e. inventory-taking has failed
and we should exit unsuccessfully, but not necessarily right
this instant)."""
def __init__(self, log_fname, debug, progress):
self.logf = open(log_fname, "w")
self.debug = debug
self.progress = progress
self.column = 0
self.error_occurred = 0
# Force the locale to "C" both for this process and all
# subsequently invoked subprocesses.
for k in os.environ.keys():
if k[:3] == "LC_" or k[:4] == "LANG":
del os.environ[k]
os.environ["LANG"] = "C"
os.environ["LANGUAGE"] = "C"
os.environ["LC_ALL"] = "C"
locale.setlocale(locale.LC_ALL, "C")
# Rejigger standard I/O streams. After this operation, file
# descriptor 0 reads from /dev/null, whereas descriptors 1 and
# 2 write to /dev/null; sys.stdin is closed; and sys.stdout
# and sys.stderr have been replaced with new file objects
# writing to wherever they used to write to, but with their
# underlying file descriptors moved above 2. The point of
# this exercise is to ensure that processes invoked via
# os.system (see above) cannot interfere with our output or
# get stuck trying to read from our input. (The output part
# is defense-in-depth, as they are always invoked with
# explicit output redirections.) The interpreter cannot be
# persuaded to close the C-level stdin, stdout, or stderr
# objects, but they shouldn't get used after this point.
try:
devnull = os.devnull
except AttributeError:
if sys.platform == "win32":
devnull = "nul"
else:
devnull = "/dev/null"
ifd = os.open(devnull, os.O_RDONLY)
sys.stdin.close()
sys.__stdin__.close()
os.dup2(ifd, 0)
os.close(ifd)
ofd = os.open(devnull, os.O_WRONLY)
orig_stdout = os.dup(1)
sys.stdout = os.fdopen(orig_stdout, "w")
sys.__stdout__ = sys.stdout
os.dup2(ofd, 1)
orig_stderr = os.dup(2)
sys.stderr = os.fdopen(orig_stderr, "w")
sys.__stderr__ = sys.stderr
os.dup2(ofd, 2)
os.close(ofd)
def log(self, msg, output=[]):
"""Write MSG to the log file, followed by OUTPUT if any.
Expected use pattern is for OUTPUT to be the contents of a file
as returned by universal_readlines(), e.g. code about to be
compiled, or error messages coming back. Forces a carriage
return after MSG and after each element of OUTPUT."""
self.logf.write(msg.rstrip())
self.logf.write('\n')
for line in output:
self.logf.write(("| %s" % line).rstrip())
self.logf.write('\n')
self.logf.flush()
def debug_log(self, msg, output=[]):
"""As above, but OUTPUT is only logged if self.debug is true."""
self.logf.write(msg.rstrip())
self.logf.write('\n')
if self.debug:
for line in output:
self.logf.write(("| %s" % line).rstrip())
self.logf.write('\n')
self.logf.flush()
def begin_test(self, msg):
"""Announce the commencement of a test, both in the log file and
on stderr."""
msg = msg.strip()
self.log("Begin test: %s" % msg)
if self.progress:
if self.column > 0:
sys.stderr.write("\n")
sys.stderr.write(msg)
sys.stderr.write("..")
sys.stderr.flush()
self.column = len(msg) + 2
def progress_tick(self):
"""Indicate on stderr that forward progress is being made.
Should normally be paired with one or more calls to log()."""
if self.progress:
if self.column > 76:
sys.stderr.write("\n ")
self.column = 3
sys.stderr.write(".")
self.column += 1
sys.stderr.flush()
def progress_note(self, msg):
"""Indicate status in the middle of an ongoing test.
MSG is sent both to stderr and to the logfile, and a carriage
return is forced before and after MSG if necessary."""
msg = msg.strip()
self.log(msg)
if self.progress:
if self.column > 0:
sys.stderr.write("\n")
sys.stderr.write(wrap_diagnostic(msg))
sys.stderr.write("\n")
sys.stderr.flush()
self.column = 0
def debug_progress_note(self, msg):
"""As above, but only prints to stderr if self.debug is true."""
msg = msg.strip()
self.log(msg)
if self.progress and self.debug:
if self.column > 0:
sys.stderr.write("\n")
sys.stderr.write(wrap_diagnostic(msg))
sys.stderr.write("\n")
sys.stderr.flush()
self.column = 0
def end_test(self, msg):
"""Announce the completion of a test, both in the log file
and on stderr."""
msg = msg.strip()
self.log("Test complete: %s" % msg)
if self.progress:
if self.column + len(msg) + 1 <= 76:
sys.stderr.write(" %s\n" % msg)
else:
sys.stderr.write("\n ")
sys.stderr.write(wrap_diagnostic(msg))
sys.stderr.write("\n")
sys.stderr.flush()
self.column = 0
def error(self, msg):
"""Announce an error severe enough that we cannot produce
meaningful output, but not so severe that we must abandon
the test run immediately."""
msg = "Error: %s" % msg
self.log(msg)
if self.column > 0:
sys.stderr.write("\n")
sys.stderr.write(wrap_diagnostic(msg))
sys.stderr.write("\n")
self.column = 0
self.error_occurred = 1
def fatal(self, msg):
"""Announce an error severe enough that the test run should
be aborted immediately. Does not return."""
msg = "Fatal error: %s" % msg
self.log(msg)
if self.column > 0:
sys.stderr.write("\n")
sys.stderr.write(wrap_diagnostic(msg))
sys.stderr.write("\n")
self.column = 0
self.error_occurred = 1
sys.exit(1)
def invoke(self, argv):
"""Invoke the command in ARGV, capturing and logging all its
output and its exit code."""
# For a wonder, the incantation to redirect both stdout and
# stderr to a file is exactly the same on Windows as on Unix!
# We put the redirections first on the command line because
# CMD.EXE may include a trailing space in the string it passes
# to CreateProcess() if they're last. Yeeeeeah.
rc = -1
msg = []
result = None
try:
try:
result = named_tmpfile(prefix="out", suffix="txt")
cmdline = ">" + result + " 2>&1 " + list2shell(argv)
msg.append(cmdline)
rc = os.system(cmdline)
if rc != 0:
if sys.platform == 'win32':
msg.append("[exit %08x]" % rc)
elif os.WIFEXITED(rc):
msg.append("[exit %d]" % os.WEXITSTATUS(rc))
elif os.WIFSIGNALED(rc):
msg.append("[signal %d]" % os.WTERMSIG(rc))
# special check for ^C and ^\ (SIGINT, SIGQUIT:
# respectively signal numbers 2 and 3, everywhere)
if os.WTERMSIG(rc) == 2 or os.WTERMSIG(rc) == 3:
raise KeyboardInterrupt
else:
msg.append("[status %08x]" % rc)
msg.extend(universal_readlines(result))
except EnvironmentError, e:
if e.filename:
msg.append("%s: %s" % (e.filename, e.strerror))
else:
msg.append("%s: %s" % (argv[0], e.strerror))
finally:
delete_if_exists(result)
self.log(msg[0], msg[1:])
return (rc, msg)
def report_errors(self, fp):
"""Print a summary of all the errors that occurred in this run."""
pass#stub
#
# Code generation for decltests (used by Header.test_contents, far below)
#
idchars = string.letters + string.digits + "_"
def mkdeclarator(dtype, name):
"""Construct a 'declarator' -- a C expression which declares NAME as an
object of type DTYPE. Relies on manual annotation to know where to
put the name: if there is a dollar sign somewhere in DTYPE, that is
replaced with the name, otherwise the name is tacked on the end."""
ds = splitto(dtype, "$", 2)
if name == "": # for function prototypes with argument name omitted
return ds[0] + ds[1]
elif ds[0][-1] in idchars:
return ds[0] + " " + name + ds[1]
else:
return ds[0] + name + ds[1]
def mk_pointer_to(dtype):
"""Given a C type expression DTYPE, return the expression for a pointer
to that type. Uses the same annotation convention as above: if there
is a dollar sign somewhere in DTYPE, a star is inserted immediately
before it, otherwise it is tacked on the end."""
ds = splitto(dtype, "$", 2)
if ds[0][-1] == "*" or ds[0][-1] == " ":
rv = ds[0] + "*"
else:
rv = ds[0] + " *"
if ds[1] == "":
return rv
else:
return rv + "$" + ds[1]
def crunch_fncall(val):
"""Given a function specification, VAL, of the form
RTYPE ":" ARGTYPE ["," ARGTYPE]... ["..." ARGTYPE ["," ARGTYPE]...]
extract and return, as a tuple, in this order, the variable parts
of the definition of a function that will call this function:
* the function's return type expression
* the function's prototype expression (that is, a list of argument
types -- without function-call parentheses)
* a prototype expression for the *definition* of a function that
will call the function (i.e. including the optional arguments
and giving formal parameter names)
* a call expression for the function (just the part that goes
inside the function-call parentheses)
* whether or not to put "return " before the function call.
See TestFunctions and TestFnMacros for usage."""
(rtype, argtypes) = splitto(val, ":", 2)
rtype = rtype.strip()
argtypes = argtypes.strip()
if argtypes == "" or argtypes == "void":
argtypes = "void"
argdecl = "void"
call = ""
else:
mandatory, rest = splitto(argtypes, ", ...", 2)
argtypes = [x.strip() for x in mandatory.split(",")]
if len(rest) > 0:
calltypes = argtypes[:]
argtypes.append("...")
calltypes.extend([x.strip() for x in rest.split(",")])
else:
calltypes = argtypes
argtypes = ", ".join([mkdeclarator(x, "") for x in argtypes])
call = []
argdecl = []
for t, v in zip(calltypes, string.letters[:len(calltypes)]):
if len(t) >= 7 and t[:5] == "expr(" and t[-1] == ")":
call.append(t[5:-1])
else:
call.append(v)
argdecl.append(mkdeclarator(t, v))
call = ", ".join(call)
argdecl = ", ".join(argdecl)
if rtype == "" or rtype == "void":
return_ = ""
else:
return_ = "return "
return (rtype, argtypes, argdecl, call, return_)
class TestItem:
"""Base class for individual content test cases.
Test items have a _tag_ which should correspond to the symbol being
tested, plus a _standard_ and _module_ which categorize the symbol
(see content_tests/CATEGORIES.ini). They all start out _enabled_, and
tests which fail are disabled until all remaining tests pass; the
set of disabled tests corresponds to the set of unavailable or
incorrectly defined symbols. Finally, the _meaning_ may be one of
self.MISSING (if this test fails, the symbol is not defined at all);
self.INCORRECT (if this test fails, the symbol is defined
incorrectly); or self.UNCERTAIN (if this test fails, the symbol is
either unavailable or incorrect; we can't tell which).
Each test is generated on exactly one line, so that we don't have
to understand compiler errors beyond the line they're on."""
MISSING = 'M'
INCORRECT = 'W'
UNCERTAIN = 'X'
def __init__(self, infname, std, mod, tag, meaning):
"""Subclasses will need to extend this constructor to save
information about the specific thing being tested."""
self.infname = infname
self.std = std
self.mod = mod
self.tag = tag
self.meaning = meaning
self.enabled = 1
self.name = None
self.lineno = None
def generate(self, out):
"""Public interface to append the code for this test to OUT.
Subclasses should not need to tamper with this method."""
if not self.enabled: return
lineno = len(out) + 1
if self.name is None:
self.lineno = lineno
self.name = "t_" + str(self.lineno)
else:
if self.lineno < lineno:
raise RuntimeError("%s (%s:%s): line numbers out of sync "
" (want %d, already at %d)"
% (self.tag, self.std, self.mod,
self.lineno, lineno))
out.extend([""] * (self.lineno - lineno))
self._generate(out)
def _generate(self, out):
"""Subclasses must override this stub method to emit the actual
code for their test case."""
raise NotImplementedError
class TestDecl(TestItem):
"""Test item which works by declaring a global variable with a
specific type, possibly with an initializer, possibly wrapped in an
#if or #ifdef conditional."""
def __init__(self, infname, std, mod, tag, meaning,
dtype, init="", cond=""):
TestItem.__init__(self, infname, std, mod, tag, meaning)
self.dtype = squishwhite(dtype)
self.init = squishwhite(init)
self.cond = squishwhite(cond)
def _generate(self, out):
decl = mkdeclarator(self.dtype, self.name)
if self.cond != "":
if self.cond[0] == '?':
out.append("#if %s" % self.cond[1:])
else:
out.append("#ifdef %s" % self.cond)
if self.init == "":
out.append(decl + ";")
else:
out.append("%s = %s;" % (decl, self.init))
if self.cond != "":
out.append("#endif")
class TestFn(TestItem):
"""Test item which works by defining a function with a particular
return type, argument list, and body. If the body is empty, the
function is just declared, not defined.
Note that if all three optional arguments are empty, what you get is
"void t_NNN(void);" which isn't particularly useful."""
def __init__(self, infname, std, mod, tag, meaning,
rtype="", argv="", body=""):
TestItem.__init__(self, infname, std, mod, tag, meaning)
self.rtype = squishwhite(rtype)
self.argv = squishwhite(argv)
self.body = squishwhite(body)
if self.rtype == "": self.rtype = "void"
if self.argv == "": self.argv = "void"
if self.body != "" and self.body[-1] != ";":
self.body = self.body + ";"
def _generate(self, out):
# To declare a function that returns a function pointer without
# benefit of typedefs, you write
# T (*fn(ARGS))(PROTO) { ... }
# where ARGS are the function's arguments, and PROTO is
# the *returned function pointer*'s prototype.
name = "%s(%s)" % (self.name, self.argv)
decl = mkdeclarator(self.rtype, name)