Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

356 lines
14 KiB

  1. # -*- Python -*-
  2. # Copyright 2008 Google Inc. All Rights Reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above
  11. # copyright notice, this list of conditions and the following disclaimer
  12. # in the documentation and/or other materials provided with the
  13. # distribution.
  14. # * Neither the name of Google Inc. nor the names of its
  15. # contributors may be used to endorse or promote products derived from
  16. # this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #
  30. # Author: [email protected] (Joi Sigurdsson)
  31. # Author: [email protected] (Vlad Losev)
  32. #
  33. # Shared SCons utilities for building Google Test inside and outside of
  34. # Google's environment.
  35. #
  36. EnsurePythonVersion(2, 3)
  37. BUILD_DIR_PREFIX = 'build'
  38. class SConstructHelper:
  39. def __init__(self):
  40. # A dictionary to look up an environment by its name.
  41. self.env_dict = {}
  42. def Initialize(self, build_root_path, support_multiple_win_builds=False):
  43. test_env = Environment()
  44. platform = test_env['PLATFORM']
  45. if platform == 'win32':
  46. if support_multiple_win_builds:
  47. available_build_types = ['win-dbg8', 'win-opt8', 'win-dbg', 'win-opt']
  48. else:
  49. available_build_types = ['win-dbg', 'win-opt']
  50. elif platform == 'darwin': # MacOSX
  51. available_build_types = ['mac-dbg', 'mac-opt']
  52. else:
  53. available_build_types = ['dbg', 'opt'] # Assuming POSIX-like environment
  54. # with GCC by default.
  55. vars = Variables()
  56. vars.Add(ListVariable('BUILD', 'Build type', available_build_types[0],
  57. available_build_types))
  58. vars.Add(BoolVariable('GTEST_BUILD_SAMPLES', 'Build samples', False))
  59. # Create base environment.
  60. self.env_base = Environment(variables=vars,
  61. BUILD_MODE={'BUILD' : '"${BUILD}"'})
  62. # Leave around a variable pointing at the build root so that SConscript
  63. # files from outside our project root can find their bearings. Trick
  64. # borrowed from Hammer in Software Construction Toolkit
  65. # (http://code.google.com/p/swtoolkit/); if/when we switch to using the
  66. # Hammer idioms instead of just Hammer's version of SCons, we should be
  67. # able to remove this line.
  68. self.env_base['SOURCE_ROOT'] = self.env_base.Dir(build_root_path)
  69. # And another that definitely always points to the project root.
  70. self.env_base['PROJECT_ROOT'] = self.env_base.Dir('.').abspath
  71. # Enable scons -h
  72. Help(vars.GenerateHelpText(self.env_base))
  73. class EnvCreator:
  74. """Creates new customized environments from a base one."""
  75. def _Remove(cls, env, attribute, value):
  76. """Removes the given attribute value from the environment."""
  77. attribute_values = env[attribute]
  78. if value in attribute_values:
  79. attribute_values.remove(value)
  80. _Remove = classmethod(_Remove)
  81. def Create(cls, base_env, modifier=None):
  82. # User should NOT create more than one environment with the same
  83. # modifier (including None).
  84. env = base_env.Clone()
  85. if modifier:
  86. modifier(env)
  87. else:
  88. env['OBJ_SUFFIX'] = '' # Default suffix for unchanged environment.
  89. return env;
  90. Create = classmethod(Create)
  91. # Each of the following methods modifies the environment for a particular
  92. # purpose and can be used by clients for creating new environments. Each
  93. # one needs to set the OBJ_SUFFIX variable to a unique suffix to
  94. # differentiate targets built with that environment. Otherwise, SCons may
  95. # complain about same target built with different settings.
  96. def UseOwnTuple(cls, env):
  97. """Instructs Google Test to use its internal implementation of tuple."""
  98. env['OBJ_SUFFIX'] = '_use_own_tuple'
  99. env.Append(CPPDEFINES = 'GTEST_USE_OWN_TR1_TUPLE=1')
  100. UseOwnTuple = classmethod(UseOwnTuple)
  101. def WarningOk(cls, env):
  102. """Does not treat warnings as errors.
  103. Necessary for compiling gtest_unittest.cc, which triggers a gcc
  104. warning when testing EXPECT_EQ(NULL, ptr)."""
  105. env['OBJ_SUFFIX'] = '_warning_ok'
  106. if env['PLATFORM'] == 'win32':
  107. cls._Remove(env, 'CCFLAGS', '-WX')
  108. else:
  109. cls._Remove(env, 'CCFLAGS', '-Werror')
  110. WarningOk = classmethod(WarningOk)
  111. def WithExceptions(cls, env):
  112. """Re-enables exceptions."""
  113. env['OBJ_SUFFIX'] = '_ex'
  114. if env['PLATFORM'] == 'win32':
  115. env.Append(CCFLAGS=['/EHsc'])
  116. env.Append(CPPDEFINES='_HAS_EXCEPTIONS=1')
  117. # Undoes the _TYPEINFO_ hack, which is unnecessary and only creates
  118. # trouble when exceptions are enabled.
  119. cls._Remove(env, 'CPPDEFINES', '_TYPEINFO_')
  120. cls._Remove(env, 'CPPDEFINES', '_HAS_EXCEPTIONS=0')
  121. else:
  122. env.Append(CCFLAGS='-fexceptions')
  123. cls._Remove(env, 'CCFLAGS', '-fno-exceptions')
  124. WithExceptions = classmethod(WithExceptions)
  125. def LessOptimized(cls, env):
  126. """Disables certain optimizations on Windows.
  127. We need to disable some optimization flags for some tests on
  128. Windows; otherwise the redirection of stdout does not work
  129. (apparently because of a compiler bug)."""
  130. env['OBJ_SUFFIX'] = '_less_optimized'
  131. if env['PLATFORM'] == 'win32':
  132. for flag in ['/O1', '/Os', '/Og', '/Oy']:
  133. cls._Remove(env, 'LINKFLAGS', flag)
  134. LessOptimized = classmethod(LessOptimized)
  135. def WithThreads(cls, env):
  136. """Allows use of threads.
  137. Currently only enables pthreads under GCC."""
  138. env['OBJ_SUFFIX'] = '_with_threads'
  139. if env['PLATFORM'] != 'win32':
  140. # Assuming POSIX-like environment with GCC.
  141. # TODO([email protected]): sniff presence of pthread_atfork instead of
  142. # selecting on a platform.
  143. env.Append(CCFLAGS=['-pthread'])
  144. env.Append(LINKFLAGS=['-pthread'])
  145. WithThreads = classmethod(WithThreads)
  146. def NoRtti(cls, env):
  147. """Disables RTTI support."""
  148. env['OBJ_SUFFIX'] = '_no_rtti'
  149. if env['PLATFORM'] == 'win32':
  150. env.Append(CCFLAGS=['/GR-'])
  151. else:
  152. env.Append(CCFLAGS=['-fno-rtti'])
  153. env.Append(CPPDEFINES='GTEST_HAS_RTTI=0')
  154. NoRtti = classmethod(NoRtti)
  155. def AllowVc71StlWithoutExceptions(self, env):
  156. env.Append(
  157. CPPDEFINES = [# needed for using some parts of STL with exception
  158. # disabled. The scoop is given here, with comments
  159. # from P.J. Plauger at
  160. # http://groups.google.com/group/microsoft.public.vc.stl/browse_thread/thread/5e719833c6bdb177?q=_HAS_EXCEPTIONS+using+namespace+std&pli=1
  161. '_TYPEINFO_'])
  162. def MakeWinBaseEnvironment(self):
  163. win_base = self.env_base.Clone(
  164. platform='win32',
  165. CCFLAGS=['-GS', # Enable buffer security check
  166. '-W4', # Warning level
  167. # Disables warnings that are either uninteresting or
  168. # hard to fix.
  169. '-WX', # Treat warning as errors
  170. #'-GR-', # Disable runtime type information
  171. '-RTCs', # Enable stack-frame run-time error checks
  172. '-RTCu', # Report when variable used without init.
  173. #'-EHs', # enable C++ EH (no SEH exceptions)
  174. '-nologo', # Suppress logo line
  175. '-J', # All chars unsigned
  176. #'-Wp64', # Detect 64-bit portability issues. This
  177. # flag has been deprecated by VS 2008.
  178. '-Zi', # Produce debug information in PDB files.
  179. ],
  180. CCPDBFLAGS='',
  181. CPPDEFINES=['_UNICODE', 'UNICODE',
  182. 'WIN32', '_WIN32',
  183. 'STRICT',
  184. 'WIN32_LEAN_AND_MEAN',
  185. '_HAS_EXCEPTIONS=0',
  186. ],
  187. LIBPATH=['#/$MAIN_DIR/lib'],
  188. LINKFLAGS=['-MACHINE:x86', # Enable safe SEH (not supp. on x64)
  189. '-DEBUG', # Generate debug info
  190. '-NOLOGO', # Suppress logo line
  191. ],
  192. # All strings in string tables zero terminated.
  193. RCFLAGS=['-n'])
  194. return win_base
  195. def SetBuildNameAndDir(self, env, name):
  196. env['BUILD_NAME'] = name;
  197. env['BUILD_DIR'] = '%s/%s' % (BUILD_DIR_PREFIX, name)
  198. self.env_dict[name] = env
  199. def MakeWinDebugEnvironment(self, base_environment, name):
  200. """Takes a VC71 or VC80 base environment and adds debug settings."""
  201. debug_env = base_environment.Clone()
  202. self.SetBuildNameAndDir(debug_env, name)
  203. debug_env.Append(
  204. CCFLAGS = ['-Od', # Disable optimizations
  205. '-MTd', # Multithreaded, static link (debug)
  206. # Path for PDB files
  207. '-Fd%s\\' % debug_env.Dir(debug_env['BUILD_DIR']),
  208. ],
  209. CPPDEFINES = ['DEBUG',
  210. '_DEBUG',
  211. ],
  212. LIBPATH = [],
  213. LINKFLAGS = ['-INCREMENTAL:yes',
  214. '/OPT:NOICF',
  215. ]
  216. )
  217. return debug_env
  218. def MakeWinOptimizedEnvironment(self, base_environment, name):
  219. """Takes a VC71 or VC80 base environment and adds release settings."""
  220. optimized_env = base_environment.Clone()
  221. self.SetBuildNameAndDir(optimized_env, name)
  222. optimized_env.Append(
  223. CCFLAGS = ['-GL', # Enable link-time code generation (/GL)
  224. '-GF', # Enable String Pooling (/GF)
  225. '-MT', # Multithreaded, static link
  226. # Path for PDB files
  227. '-Fd%s\\' % optimized_env.Dir(optimized_env['BUILD_DIR']),
  228. # Favor small code (this is /O1 minus /Og)
  229. '-Os',
  230. '-Oy',
  231. '-Ob2',
  232. '-Gs',
  233. '-GF',
  234. '-Gy',
  235. ],
  236. CPPDEFINES = ['NDEBUG',
  237. '_NDEBUG',
  238. ],
  239. LIBPATH = [],
  240. ARFLAGS = ['-LTCG'], # Link-time Code Generation
  241. LINKFLAGS = ['-LTCG', # Link-time Code Generation
  242. '-OPT:REF', # Optimize by reference.
  243. '-OPT:ICF=32', # Optimize by identical COMDAT folding
  244. '-OPT:NOWIN98', # Optimize by not aligning section for
  245. # Win98
  246. '-INCREMENTAL:NO', # No incremental linking as we don't
  247. # want padding bytes in release build.
  248. ],
  249. )
  250. return optimized_env
  251. def AddGccFlagsTo(self, env, optimized):
  252. env.Append(CCFLAGS=['-fno-exceptions',
  253. '-Wall',
  254. '-Werror',
  255. ])
  256. if optimized:
  257. env.Append(CCFLAGS=['-O2'], CPPDEFINES=['NDEBUG', '_NDEBUG'])
  258. else:
  259. env.Append(CCFLAGS=['-g'], CPPDEFINES=['DEBUG', '_DEBUG'])
  260. def ConfigureGccEnvironments(self):
  261. # Mac environments.
  262. mac_base = self.env_base.Clone(platform='darwin')
  263. mac_dbg = mac_base.Clone()
  264. self.AddGccFlagsTo(mac_dbg, optimized=False)
  265. self.SetBuildNameAndDir(mac_dbg, 'mac-dbg')
  266. mac_opt = mac_base.Clone()
  267. self.AddGccFlagsTo(mac_opt, optimized=True)
  268. self.SetBuildNameAndDir(mac_opt, 'mac-opt')
  269. # Generic GCC environments.
  270. gcc_dbg = self.env_base.Clone()
  271. self.AddGccFlagsTo(gcc_dbg, optimized=False)
  272. self.SetBuildNameAndDir(gcc_dbg, 'dbg')
  273. gcc_opt = self.env_base.Clone()
  274. self.AddGccFlagsTo(gcc_opt, optimized=True)
  275. self.SetBuildNameAndDir(gcc_opt, 'opt')
  276. def BuildSelectedEnvironments(self):
  277. EnvCreator = SConstructHelper.EnvCreator
  278. Export('EnvCreator')
  279. # Build using whichever environments the 'BUILD' option selected
  280. for build_name in self.env_base['BUILD']:
  281. print 'BUILDING %s' % build_name
  282. env = self.env_dict[build_name]
  283. # Make sure SConscript files can refer to base build dir
  284. env['MAIN_DIR'] = env.Dir(env['BUILD_DIR'])
  285. #print 'CCFLAGS: %s' % env.subst('$CCFLAGS')
  286. #print 'LINK: %s' % env.subst('$LINK')
  287. #print 'AR: %s' % env.subst('$AR')
  288. #print 'CC: %s' % env.subst('$CC')
  289. #print 'CXX: %s' % env.subst('$CXX')
  290. #print 'LIBPATH: %s' % env.subst('$LIBPATH')
  291. #print 'ENV:PATH: %s' % env['ENV']['PATH']
  292. #print 'ENV:INCLUDE: %s' % env['ENV']['INCLUDE']
  293. #print 'ENV:LIB: %s' % env['ENV']['LIB']
  294. #print 'ENV:TEMP: %s' % env['ENV']['TEMP']
  295. Export('env')
  296. # Invokes SConscript with variant_dir being build/<config name>.
  297. # Counter-intuitively, src_dir is relative to the build dir and has
  298. # to be '..' to point to the scons directory.
  299. SConscript('SConscript',
  300. src_dir='..',
  301. variant_dir=env['BUILD_DIR'],
  302. duplicate=0)
  303. sconstruct_helper = SConstructHelper()
  304. Return('sconstruct_helper')