1 """SCons.SConf
2
3 Autoconf-like configuration support.
4
5 In other words, SConf allows to run tests on the build machine to detect
6 capabilities of system and do some things based on result: generate config
7 files, header files for C/C++, update variables in environment.
8
9 Tests on the build system can detect if compiler sees header files, if
10 libraries are installed, if some command line options are supported etc.
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 __revision__ = "src/engine/SCons/SConf.py 2014/09/27 12:51:43 garyo"
38
39 import SCons.compat
40
41 import io
42 import os
43 import re
44 import sys
45 import traceback
46
47 import SCons.Action
48 import SCons.Builder
49 import SCons.Errors
50 import SCons.Job
51 import SCons.Node.FS
52 import SCons.Taskmaster
53 import SCons.Util
54 import SCons.Warnings
55 import SCons.Conftest
56
57 from SCons.Debug import Trace
58
59
60 SCons.Conftest.LogInputFiles = 0
61 SCons.Conftest.LogErrorMessages = 0
62
63
64 build_type = None
65 build_types = ['clean', 'help']
66
70
71
72 dryrun = 0
73
74 AUTO=0
75 FORCE=1
76 CACHE=2
77 cache_mode = AUTO
78
80 """Set the Configure cache mode. mode must be one of "auto", "force",
81 or "cache"."""
82 global cache_mode
83 if mode == "auto":
84 cache_mode = AUTO
85 elif mode == "force":
86 cache_mode = FORCE
87 elif mode == "cache":
88 cache_mode = CACHE
89 else:
90 raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode)
91
92 progress_display = SCons.Util.display
97
98 SConfFS = None
99
100 _ac_build_counter = 0
101 _ac_config_logs = {}
102 _ac_config_hs = {}
103 sconf_global = None
104
106 t = open(str(target[0]), "w")
107 defname = re.sub('[^A-Za-z0-9_]', '_', str(target[0]).upper())
108 t.write("""#ifndef %(DEFNAME)s_SEEN
109 #define %(DEFNAME)s_SEEN
110
111 """ % {'DEFNAME' : defname})
112 t.write(source[0].get_contents())
113 t.write("""
114 #endif /* %(DEFNAME)s_SEEN */
115 """ % {'DEFNAME' : defname})
116 t.close()
117
119 return "scons: Configure: creating " + str(target[0])
120
121
123 if len(_ac_config_hs) == 0:
124 return False
125 else:
126 return True
127
136
137
140 SCons.Warnings.enableWarningClass(SConfWarning)
141
142
146
156
162
163
169 return (str(target[0]) + ' <-\n |' +
170 source[0].get_contents().replace( '\n', "\n |" ) )
171
173 """
174 Special build info for targets of configure tests. Additional members
175 are result (did the builder succeed last time?) and string, which
176 contains messages of the original build phase.
177 """
178 result = None
179 string = None
180
184
185
187 """
188 'Sniffer' for a file-like writable object. Similar to the unix tool tee.
189 """
191 self.orig = orig
192 self.s = io.StringIO()
193
195 if self.orig:
196 self.orig.write(str)
197 try:
198 self.s.write(str)
199 except TypeError as e:
200 if e.message.startswith('unicode argument expected'):
201 self.s.write(str.decode())
202 else:
203 raise
204
206 for l in lines:
207 self.write(l + '\n')
208
210 """
211 Return everything written to orig since the Streamer was created.
212 """
213 return self.s.getvalue()
214
216 if self.orig:
217 self.orig.flush()
218 self.s.flush()
219
220
222 """
223 This is almost the same as SCons.Script.BuildTask. Handles SConfErrors
224 correctly and knows about the current cache_mode.
225 """
229
231 """
232 Logs the original builder messages, given the SConfBuildInfo instance
233 bi.
234 """
235 if not isinstance(bi, SConfBuildInfo):
236 SCons.Warnings.warn(SConfWarning,
237 "The stored build information has an unexpected class: %s" % bi.__class__)
238 else:
239 self.display("The original builder output was:\n" +
240 (" |" + str(bi.string)).replace("\n", "\n |"))
241
243
244
245 exc_type = self.exc_info()[0]
246 if issubclass(exc_type, SConfError):
247 raise
248 elif issubclass(exc_type, SCons.Errors.BuildError):
249
250
251
252 self.exc_clear()
253 else:
254 self.display('Caught exception while building "%s":\n' %
255 self.targets[0])
256 try:
257 excepthook = sys.excepthook
258 except AttributeError:
259
260 def excepthook(type, value, tb):
261 traceback.print_tb(tb)
262 print type, value
263 excepthook(*self.exc_info())
264 return SCons.Taskmaster.Task.failed(self)
265
300
341 if env.decide_source.func_code is not force_build.func_code:
342 env.Decider(force_build)
343 env['PSTDOUT'] = env['PSTDERR'] = s
344 try:
345 sconf.cached = 0
346 self.targets[0].build()
347 finally:
348 sys.stdout = sys.stderr = env['PSTDOUT'] = \
349 env['PSTDERR'] = sconf.logstream
350 except KeyboardInterrupt:
351 raise
352 except SystemExit:
353 exc_value = sys.exc_info()[1]
354 raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code)
355 except Exception, e:
356 for t in self.targets:
357 binfo = t.get_binfo()
358 binfo.__class__ = SConfBuildInfo
359 binfo.set_build_result(1, s.getvalue())
360 sconsign_entry = SCons.SConsign.SConsignEntry()
361 sconsign_entry.binfo = binfo
362
363
364
365
366
367
368
369 sconsign = t.dir.sconsign()
370 sconsign.set_entry(t.name, sconsign_entry)
371 sconsign.merge()
372 raise e
373 else:
374 for t in self.targets:
375 binfo = t.get_binfo()
376 binfo.__class__ = SConfBuildInfo
377 binfo.set_build_result(0, s.getvalue())
378 sconsign_entry = SCons.SConsign.SConsignEntry()
379 sconsign_entry.binfo = binfo
380
381
382
383
384
385
386
387 sconsign = t.dir.sconsign()
388 sconsign.set_entry(t.name, sconsign_entry)
389 sconsign.merge()
390
392 """This is simply a class to represent a configure context. After
393 creating a SConf object, you can call any tests. After finished with your
394 tests, be sure to call the Finish() method, which returns the modified
395 environment.
396 Some words about caching: In most cases, it is not necessary to cache
397 Test results explicitely. Instead, we use the scons dependency checking
398 mechanism. For example, if one wants to compile a test program
399 (SConf.TryLink), the compiler is only called, if the program dependencies
400 have changed. However, if the program could not be compiled in a former
401 SConf run, we need to explicitely cache this error.
402 """
403
404 - def __init__(self, env, custom_tests = {}, conf_dir='$CONFIGUREDIR',
405 log_file='$CONFIGURELOG', config_h = None, _depth = 0):
406 """Constructor. Pass additional tests in the custom_tests-dictinary,
407 e.g. custom_tests={'CheckPrivate':MyPrivateTest}, where MyPrivateTest
408 defines a custom test.
409 Note also the conf_dir and log_file arguments (you may want to
410 build tests in the VariantDir, not in the SourceDir)
411 """
412 global SConfFS
413 if not SConfFS:
414 SConfFS = SCons.Node.FS.default_fs or \
415 SCons.Node.FS.FS(env.fs.pathTop)
416 if sconf_global is not None:
417 raise SCons.Errors.UserError
418 self.env = env
419 if log_file is not None:
420 log_file = SConfFS.File(env.subst(log_file))
421 self.logfile = log_file
422 self.logstream = None
423 self.lastTarget = None
424 self.depth = _depth
425 self.cached = 0
426
427
428 default_tests = {
429 'CheckCC' : CheckCC,
430 'CheckCXX' : CheckCXX,
431 'CheckSHCC' : CheckSHCC,
432 'CheckSHCXX' : CheckSHCXX,
433 'CheckFunc' : CheckFunc,
434 'CheckType' : CheckType,
435 'CheckTypeSize' : CheckTypeSize,
436 'CheckDeclaration' : CheckDeclaration,
437 'CheckHeader' : CheckHeader,
438 'CheckCHeader' : CheckCHeader,
439 'CheckCXXHeader' : CheckCXXHeader,
440 'CheckLib' : CheckLib,
441 'CheckLibWithHeader' : CheckLibWithHeader,
442 }
443 self.AddTests(default_tests)
444 self.AddTests(custom_tests)
445 self.confdir = SConfFS.Dir(env.subst(conf_dir))
446 if config_h is not None:
447 config_h = SConfFS.File(config_h)
448 self.config_h = config_h
449 self._startup()
450
452 """Call this method after finished with your tests:
453 env = sconf.Finish()
454 """
455 self._shutdown()
456 return self.env
457
458 - def Define(self, name, value = None, comment = None):
459 """
460 Define a pre processor symbol name, with the optional given value in the
461 current config header.
462
463 If value is None (default), then #define name is written. If value is not
464 none, then #define name value is written.
465
466 comment is a string which will be put as a C comment in the
467 header, to explain the meaning of the value (appropriate C comments /* and
468 */ will be put automatically."""
469 lines = []
470 if comment:
471 comment_str = "/* %s */" % comment
472 lines.append(comment_str)
473
474 if value is not None:
475 define_str = "#define %s %s" % (name, value)
476 else:
477 define_str = "#define %s" % name
478 lines.append(define_str)
479 lines.append('')
480
481 self.config_h_text = self.config_h_text + '\n'.join(lines)
482
535
537 """Wrapper function for handling piped spawns.
538
539 This looks to the calling interface (in Action.py) like a "normal"
540 spawn, but associates the call with the PSPAWN variable from
541 the construction environment and with the streams to which we
542 want the output logged. This gets slid into the construction
543 environment as the SPAWN variable so Action.py doesn't have to
544 know or care whether it's spawning a piped command or not.
545 """
546 return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)
547
548
549 - def TryBuild(self, builder, text = None, extension = ""):
550 """Low level TryBuild implementation. Normally you don't need to
551 call that - you can use TryCompile / TryLink / TryRun instead
552 """
553 global _ac_build_counter
554
555
556
557 try:
558 self.pspawn = self.env['PSPAWN']
559 except KeyError:
560 raise SCons.Errors.UserError('Missing PSPAWN construction variable.')
561 try:
562 save_spawn = self.env['SPAWN']
563 except KeyError:
564 raise SCons.Errors.UserError('Missing SPAWN construction variable.')
565
566 nodesToBeBuilt = []
567
568 f = "conftest_" + str(_ac_build_counter)
569 pref = self.env.subst( builder.builder.prefix )
570 suff = self.env.subst( builder.builder.suffix )
571 target = self.confdir.File(pref + f + suff)
572
573 try:
574
575
576 self.env['SPAWN'] = self.pspawn_wrapper
577 sourcetext = self.env.Value(text)
578
579 if text is not None:
580 textFile = self.confdir.File(f + extension)
581 textFileNode = self.env.SConfSourceBuilder(target=textFile,
582 source=sourcetext)
583 nodesToBeBuilt.extend(textFileNode)
584 source = textFileNode
585 else:
586 source = None
587
588 nodes = builder(target = target, source = source)
589 if not SCons.Util.is_List(nodes):
590 nodes = [nodes]
591 nodesToBeBuilt.extend(nodes)
592 result = self.BuildNodes(nodesToBeBuilt)
593
594 finally:
595 self.env['SPAWN'] = save_spawn
596
597 _ac_build_counter = _ac_build_counter + 1
598 if result:
599 self.lastTarget = nodes[0]
600 else:
601 self.lastTarget = None
602
603 return result
604
605 - def TryAction(self, action, text = None, extension = ""):
606 """Tries to execute the given action with optional source file
607 contents <text> and optional source file extension <extension>,
608 Returns the status (0 : failed, 1 : ok) and the contents of the
609 output file.
610 """
611 builder = SCons.Builder.Builder(action=action)
612 self.env.Append( BUILDERS = {'SConfActionBuilder' : builder} )
613 ok = self.TryBuild(self.env.SConfActionBuilder, text, extension)
614 del self.env['BUILDERS']['SConfActionBuilder']
615 if ok:
616 outputStr = self.lastTarget.get_contents()
617 return (1, outputStr)
618 return (0, "")
619
621 """Compiles the program given in text to an env.Object, using extension
622 as file extension (e.g. '.c'). Returns 1, if compilation was
623 successful, 0 otherwise. The target is saved in self.lastTarget (for
624 further processing).
625 """
626 return self.TryBuild(self.env.Object, text, extension)
627
628 - def TryLink( self, text, extension ):
629 """Compiles the program given in text to an executable env.Program,
630 using extension as file extension (e.g. '.c'). Returns 1, if
631 compilation was successful, 0 otherwise. The target is saved in
632 self.lastTarget (for further processing).
633 """
634 return self.TryBuild(self.env.Program, text, extension )
635
636 - def TryRun(self, text, extension ):
637 """Compiles and runs the program given in text, using extension
638 as file extension (e.g. '.c'). Returns (1, outputStr) on success,
639 (0, '') otherwise. The target (a file containing the program's stdout)
640 is saved in self.lastTarget (for further processing).
641 """
642 ok = self.TryLink(text, extension)
643 if( ok ):
644 prog = self.lastTarget
645 pname = prog.path
646 output = self.confdir.File(os.path.basename(pname)+'.out')
647 node = self.env.Command(output, prog, [ [ pname, ">", "${TARGET}"] ])
648 ok = self.BuildNodes(node)
649 if ok:
650 outputStr = output.get_contents()
651 return( 1, outputStr)
652 return (0, "")
653
655 """A wrapper around Tests (to ensure sanity)"""
657 self.test = test
658 self.sconf = sconf
660 if not self.sconf.active:
661 raise SCons.Errors.UserError
662 context = CheckContext(self.sconf)
663 ret = self.test(context, *args, **kw)
664 if self.sconf.config_h is not None:
665 self.sconf.config_h_text = self.sconf.config_h_text + context.config_h
666 context.Result("error: no result")
667 return ret
668
669 - def AddTest(self, test_name, test_instance):
670 """Adds test_class to this SConf instance. It can be called with
671 self.test_name(...)"""
672 setattr(self, test_name, SConfBase.TestWrapper(test_instance, self))
673
675 """Adds all the tests given in the tests dictionary to this SConf
676 instance
677 """
678 for name in tests.keys():
679 self.AddTest(name, tests[name])
680
690
736
738 """Private method. Reset to non-piped spawn"""
739 global sconf_global, _ac_config_hs
740
741 if not self.active:
742 raise SCons.Errors.UserError("Finish may be called only once!")
743 if self.logstream is not None and not dryrun:
744 self.logstream.write("\n")
745 self.logstream.close()
746 self.logstream = None
747
748 blds = self.env['BUILDERS']
749 del blds['SConfSourceBuilder']
750 self.env.Replace( BUILDERS=blds )
751 self.active = 0
752 sconf_global = None
753 if not self.config_h is None:
754 _ac_config_hs[self.config_h] = self.config_h_text
755 self.env.fs = self.lastEnvFs
756
757 -class CheckContext(object):
758 """Provides a context for configure tests. Defines how a test writes to the
759 screen and log file.
760
761 A typical test is just a callable with an instance of CheckContext as
762 first argument:
763
764 def CheckCustom(context, ...)
765 context.Message('Checking my weird test ... ')
766 ret = myWeirdTestFunction(...)
767 context.Result(ret)
768
769 Often, myWeirdTestFunction will be one of
770 context.TryCompile/context.TryLink/context.TryRun. The results of
771 those are cached, for they are only rebuild, if the dependencies have
772 changed.
773 """
774
775 - def __init__(self, sconf):
776 """Constructor. Pass the corresponding SConf instance."""
777 self.sconf = sconf
778 self.did_show_result = 0
779
780
781 self.vardict = {}
782 self.havedict = {}
783 self.headerfilename = None
784 self.config_h = ""
785
786
787
788
789
790
791
792
793 - def Message(self, text):
794 """Inform about what we are doing right now, e.g.
795 'Checking for SOMETHING ... '
796 """
797 self.Display(text)
798 self.sconf.cached = 1
799 self.did_show_result = 0
800
801 - def Result(self, res):
802 """Inform about the result of the test. If res is not a string, displays
803 'yes' or 'no' depending on whether res is evaluated as true or false.
804 The result is only displayed when self.did_show_result is not set.
805 """
806 if isinstance(res, str):
807 text = res
808 elif res:
809 text = "yes"
810 else:
811 text = "no"
812
813 if self.did_show_result == 0:
814
815 self.Display(text + "\n")
816 self.did_show_result = 1
817
818 - def TryBuild(self, *args, **kw):
819 return self.sconf.TryBuild(*args, **kw)
820
821 - def TryAction(self, *args, **kw):
822 return self.sconf.TryAction(*args, **kw)
823
824 - def TryCompile(self, *args, **kw):
825 return self.sconf.TryCompile(*args, **kw)
826
827 - def TryLink(self, *args, **kw):
828 return self.sconf.TryLink(*args, **kw)
829
830 - def TryRun(self, *args, **kw):
831 return self.sconf.TryRun(*args, **kw)
832
833 - def __getattr__( self, attr ):
834 if( attr == 'env' ):
835 return self.sconf.env
836 elif( attr == 'lastTarget' ):
837 return self.sconf.lastTarget
838 else:
839 raise AttributeError("CheckContext instance has no attribute '%s'" % attr)
840
841
842
843 - def BuildProg(self, text, ext):
844 self.sconf.cached = 1
845
846 return not self.TryBuild(self.env.Program, text, ext)
847
848 - def CompileProg(self, text, ext):
849 self.sconf.cached = 1
850
851 return not self.TryBuild(self.env.Object, text, ext)
852
853 - def CompileSharedObject(self, text, ext):
854 self.sconf.cached = 1
855
856 return not self.TryBuild(self.env.SharedObject, text, ext)
857
858 - def RunProg(self, text, ext):
859 self.sconf.cached = 1
860
861 st, out = self.TryRun(text, ext)
862 return not st, out
863
864 - def AppendLIBS(self, lib_name_list):
865 oldLIBS = self.env.get( 'LIBS', [] )
866 self.env.Append(LIBS = lib_name_list)
867 return oldLIBS
868
869 - def PrependLIBS(self, lib_name_list):
870 oldLIBS = self.env.get( 'LIBS', [] )
871 self.env.Prepend(LIBS = lib_name_list)
872 return oldLIBS
873
874 - def SetLIBS(self, val):
875 oldLIBS = self.env.get( 'LIBS', [] )
876 self.env.Replace(LIBS = val)
877 return oldLIBS
878
879 - def Display(self, msg):
880 if self.sconf.cached:
881
882
883
884 msg = "(cached) " + msg
885 self.sconf.cached = 0
886 progress_display(msg, append_newline=0)
887 self.Log("scons: Configure: " + msg + "\n")
888
889 - def Log(self, msg):
890 if self.sconf.logstream is not None:
891 self.sconf.logstream.write(msg)
892
893
894
895
907
908
909 -def CheckFunc(context, function_name, header = None, language = None):
913
914 -def CheckType(context, type_name, includes = "", language = None):
915 res = SCons.Conftest.CheckType(context, type_name,
916 header = includes, language = language)
917 context.did_show_result = 1
918 return not res
919
920 -def CheckTypeSize(context, type_name, includes = "", language = None, expect = None):
921 res = SCons.Conftest.CheckTypeSize(context, type_name,
922 header = includes, language = language,
923 expect = expect)
924 context.did_show_result = 1
925 return res
926
928 res = SCons.Conftest.CheckDeclaration(context, declaration,
929 includes = includes,
930 language = language)
931 context.did_show_result = 1
932 return not res
933
935
936
937 if not SCons.Util.is_List(headers):
938 headers = [headers]
939 l = []
940 if leaveLast:
941 lastHeader = headers[-1]
942 headers = headers[:-1]
943 else:
944 lastHeader = None
945 for s in headers:
946 l.append("#include %s%s%s\n"
947 % (include_quotes[0], s, include_quotes[1]))
948 return ''.join(l), lastHeader
949
951 """
952 A test for a C or C++ header file.
953 """
954 prog_prefix, hdr_to_check = \
955 createIncludesFromHeaders(header, 1, include_quotes)
956 res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix,
957 language = language,
958 include_quotes = include_quotes)
959 context.did_show_result = 1
960 return not res
961
966
971
976
981
982
983
985 """
986 A test for a C header file.
987 """
988 return CheckHeader(context, header, include_quotes, language = "C")
989
990
991
992
994 """
995 A test for a C++ header file.
996 """
997 return CheckHeader(context, header, include_quotes, language = "C++")
998
999
1000 -def CheckLib(context, library = None, symbol = "main",
1001 header = None, language = None, autoadd = 1):
1002 """
1003 A test for a library. See also CheckLibWithHeader.
1004 Note that library may also be None to test whether the given symbol
1005 compiles without flags.
1006 """
1007
1008 if library == []:
1009 library = [None]
1010
1011 if not SCons.Util.is_List(library):
1012 library = [library]
1013
1014
1015 res = SCons.Conftest.CheckLib(context, library, symbol, header = header,
1016 language = language, autoadd = autoadd)
1017 context.did_show_result = 1
1018 return not res
1019
1020
1021
1022
1025
1026 """
1027 Another (more sophisticated) test for a library.
1028 Checks, if library and header is available for language (may be 'C'
1029 or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'.
1030 As in CheckLib, we support library=None, to test if the call compiles
1031 without extra link flags.
1032 """
1033 prog_prefix, dummy = \
1034 createIncludesFromHeaders(header, 0)
1035 if libs == []:
1036 libs = [None]
1037
1038 if not SCons.Util.is_List(libs):
1039 libs = [libs]
1040
1041 res = SCons.Conftest.CheckLib(context, libs, None, prog_prefix,
1042 call = call, language = language, autoadd = autoadd)
1043 context.did_show_result = 1
1044 return not res
1045
1046
1047
1048
1049
1050
1051