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.

635 lines
19 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. # Copyright 2010 Google Inc.
  2. # All Rights Reserved.
  3. #
  4. # Author: Tim Haloun (thaloun@google.com)
  5. # Daniel Petersson (dape@google.com)
  6. #
  7. import os
  8. import SCons.Util
  9. class LibraryInfo:
  10. """Records information on the libraries defined in a build configuration.
  11. Attributes:
  12. lib_targets: Dictionary of library target params for lookups in
  13. ExtendComponent().
  14. prebuilt_libraries: Set of all prebuilt static libraries.
  15. system_libraries: Set of libraries not found in the above (used to detect
  16. out-of-order build rules).
  17. """
  18. # Dictionary of LibraryInfo objects keyed by BUILD_TYPE value.
  19. __library_info = {}
  20. @staticmethod
  21. def get(env):
  22. """Gets the LibraryInfo object for the current build type.
  23. Args:
  24. env: The environment object.
  25. Returns:
  26. The LibraryInfo object.
  27. """
  28. return LibraryInfo.__library_info.setdefault(env['BUILD_TYPE'],
  29. LibraryInfo())
  30. def __init__(self):
  31. self.lib_targets = {}
  32. self.prebuilt_libraries = set()
  33. self.system_libraries = set()
  34. def _GetLibParams(env, lib):
  35. """Gets the params for the given library if it is a library target.
  36. Returns the params that were specified when the given lib target name was
  37. created, or None if no such lib target has been defined. In the None case, it
  38. additionally records the negative result so as to detect out-of-order
  39. dependencies for future targets.
  40. Args:
  41. env: The environment object.
  42. lib: The library's name as a string.
  43. Returns:
  44. Its dictionary of params, or None.
  45. """
  46. info = LibraryInfo.get(env)
  47. if lib in info.lib_targets:
  48. return info.lib_targets[lib]
  49. else:
  50. if lib not in info.prebuilt_libraries and lib not in info.system_libraries:
  51. info.system_libraries.add(lib)
  52. return None
  53. def _RecordLibParams(env, lib, params):
  54. """Record the params used for a library target.
  55. Record the params used for a library target while checking for several error
  56. conditions.
  57. Args:
  58. env: The environment object.
  59. lib: The library target's name as a string.
  60. params: Its dictionary of params.
  61. Raises:
  62. Exception: The lib target has already been recorded, or the lib was
  63. previously declared to be prebuilt, or the lib target is being defined
  64. after a reverse library dependency.
  65. """
  66. info = LibraryInfo.get(env)
  67. if lib in info.lib_targets:
  68. raise Exception('Multiple definitions of ' + lib)
  69. if lib in info.prebuilt_libraries:
  70. raise Exception(lib + ' already declared as a prebuilt library')
  71. if lib in info.system_libraries:
  72. raise Exception(lib + ' cannot be defined after its reverse library '
  73. 'dependencies')
  74. info.lib_targets[lib] = params
  75. def _IsPrebuiltLibrary(env, lib):
  76. """Checks whether or not the given library is a prebuilt static library.
  77. Returns whether or not the given library name has been declared to be a
  78. prebuilt static library. In the False case, it additionally records the
  79. negative result so as to detect out-of-order dependencies for future targets.
  80. Args:
  81. env: The environment object.
  82. lib: The library's name as a string.
  83. Returns:
  84. True or False
  85. """
  86. info = LibraryInfo.get(env)
  87. if lib in info.prebuilt_libraries:
  88. return True
  89. else:
  90. if lib not in info.lib_targets and lib not in info.system_libraries:
  91. info.system_libraries.add(lib)
  92. return False
  93. def _RecordPrebuiltLibrary(env, lib):
  94. """Record that a library is a prebuilt static library.
  95. Record that the given library name refers to a prebuilt static library while
  96. checking for several error conditions.
  97. Args:
  98. env: The environment object.
  99. lib: The library's name as a string.
  100. Raises:
  101. Exception: The lib has already been recorded to be prebuilt, or the lib was
  102. previously declared as a target, or the lib is being declared as
  103. prebuilt after a reverse library dependency.
  104. """
  105. info = LibraryInfo.get(env)
  106. if lib in info.prebuilt_libraries:
  107. raise Exception('Multiple prebuilt declarations of ' + lib)
  108. if lib in info.lib_targets:
  109. raise Exception(lib + ' already defined as a target')
  110. if lib in info.system_libraries:
  111. raise Exception(lib + ' cannot be declared as prebuilt after its reverse '
  112. 'library dependencies')
  113. info.prebuilt_libraries.add(lib)
  114. def _GenericLibrary(env, static, **kwargs):
  115. """Extends ComponentLibrary to support multiplatform builds
  116. of dynamic or static libraries.
  117. Args:
  118. env: The environment object.
  119. kwargs: The keyword arguments.
  120. Returns:
  121. See swtoolkit ComponentLibrary
  122. """
  123. params = CombineDicts(kwargs, {'COMPONENT_STATIC': static})
  124. return ExtendComponent(env, 'ComponentLibrary', **params)
  125. def DeclarePrebuiltLibraries(env, libraries):
  126. """Informs the build engine about external static libraries.
  127. Informs the build engine that the given external library name(s) are prebuilt
  128. static libraries, as opposed to shared libraries.
  129. Args:
  130. env: The environment object.
  131. libraries: The library or libraries that are being declared as prebuilt
  132. static libraries.
  133. """
  134. if not SCons.Util.is_List(libraries):
  135. libraries = [libraries]
  136. for library in libraries:
  137. _RecordPrebuiltLibrary(env, library)
  138. def Library(env, **kwargs):
  139. """Extends ComponentLibrary to support multiplatform builds of static
  140. libraries.
  141. Args:
  142. env: The current environment.
  143. kwargs: The keyword arguments.
  144. Returns:
  145. See swtoolkit ComponentLibrary
  146. """
  147. return _GenericLibrary(env, True, **kwargs)
  148. def DynamicLibrary(env, **kwargs):
  149. """Extends ComponentLibrary to support multiplatform builds
  150. of dynmic libraries.
  151. Args:
  152. env: The environment object.
  153. kwargs: The keyword arguments.
  154. Returns:
  155. See swtoolkit ComponentLibrary
  156. """
  157. return _GenericLibrary(env, False, **kwargs)
  158. def Object(env, **kwargs):
  159. return ExtendComponent(env, 'ComponentObject', **kwargs)
  160. def Unittest(env, **kwargs):
  161. """Extends ComponentTestProgram to support unittest built
  162. for multiple platforms.
  163. Args:
  164. env: The current environment.
  165. kwargs: The keyword arguments.
  166. Returns:
  167. See swtoolkit ComponentProgram.
  168. """
  169. kwargs['name'] = kwargs['name'] + '_unittest'
  170. common_test_params = {
  171. 'posix_cppdefines': ['GUNIT_NO_GOOGLE3', 'GTEST_HAS_RTTI=0'],
  172. 'libs': ['unittest_main', 'gunit']
  173. }
  174. if 'explicit_libs' not in kwargs:
  175. common_test_params['win_libs'] = [
  176. 'advapi32',
  177. 'crypt32',
  178. 'iphlpapi',
  179. 'secur32',
  180. 'shell32',
  181. 'shlwapi',
  182. 'user32',
  183. 'wininet',
  184. 'ws2_32'
  185. ]
  186. common_test_params['lin_libs'] = [
  187. 'crypto',
  188. 'pthread',
  189. 'ssl',
  190. ]
  191. params = CombineDicts(kwargs, common_test_params)
  192. return ExtendComponent(env, 'ComponentTestProgram', **params)
  193. def App(env, **kwargs):
  194. """Extends ComponentProgram to support executables with platform specific
  195. options.
  196. Args:
  197. env: The current environment.
  198. kwargs: The keyword arguments.
  199. Returns:
  200. See swtoolkit ComponentProgram.
  201. """
  202. if 'explicit_libs' not in kwargs:
  203. common_app_params = {
  204. 'win_libs': [
  205. 'advapi32',
  206. 'crypt32',
  207. 'iphlpapi',
  208. 'secur32',
  209. 'shell32',
  210. 'shlwapi',
  211. 'user32',
  212. 'wininet',
  213. 'ws2_32'
  214. ]}
  215. params = CombineDicts(kwargs, common_app_params)
  216. else:
  217. params = kwargs
  218. return ExtendComponent(env, 'ComponentProgram', **params)
  219. def WiX(env, **kwargs):
  220. """ Extends the WiX builder
  221. Args:
  222. env: The current environment.
  223. kwargs: The keyword arguments.
  224. Returns:
  225. The node produced by the environment's wix builder
  226. """
  227. return ExtendComponent(env, 'WiX', **kwargs)
  228. def Repository(env, at, path):
  229. """Maps a directory external to $MAIN_DIR to the given path so that sources
  230. compiled from it end up in the correct place under $OBJ_DIR. NOT required
  231. when only referring to header files.
  232. Args:
  233. env: The current environment object.
  234. at: The 'mount point' within the current directory.
  235. path: Path to the actual directory.
  236. """
  237. env.Dir(at).addRepository(env.Dir(path))
  238. def Components(*paths):
  239. """Completes the directory paths with the correct file
  240. names such that the directory/directory.scons name
  241. convention can be used.
  242. Args:
  243. paths: The paths to complete. If it refers to an existing
  244. file then it is ignored.
  245. Returns:
  246. The completed lif scons files that are needed to build talk.
  247. """
  248. files = []
  249. for path in paths:
  250. if os.path.isfile(path):
  251. files.append(path)
  252. else:
  253. files.append(ExpandSconsPath(path))
  254. return files
  255. def ExpandSconsPath(path):
  256. """Expands a directory path into the path to the
  257. scons file that our build uses.
  258. Ex: magiflute/plugin/common => magicflute/plugin/common/common.scons
  259. Args:
  260. path: The directory path to expand.
  261. Returns:
  262. The expanded path.
  263. """
  264. return '%s/%s.scons' % (path, os.path.basename(path))
  265. def ReadVersion(filename):
  266. """Executes the supplied file and pulls out a version definition from it. """
  267. defs = {}
  268. execfile(str(filename), defs)
  269. if 'version' not in defs:
  270. return '0.0.0.0'
  271. version = defs['version']
  272. parts = version.split(',')
  273. build = os.environ.get('GOOGLE_VERSION_BUILDNUMBER')
  274. if build:
  275. parts[-1] = str(build)
  276. return '.'.join(parts)
  277. #-------------------------------------------------------------------------------
  278. # Helper methods for translating talk.Foo() declarations in to manipulations of
  279. # environmuent construction variables, including parameter parsing and merging,
  280. #
  281. def PopEntry(dictionary, key):
  282. """Get the value from a dictionary by key. If the key
  283. isn't in the dictionary then None is returned. If it is in
  284. the dictionary the value is fetched and then is it removed
  285. from the dictionary.
  286. Args:
  287. dictionary: The dictionary.
  288. key: The key to get the value for.
  289. Returns:
  290. The value or None if the key is missing.
  291. """
  292. value = None
  293. if key in dictionary:
  294. value = dictionary[key]
  295. dictionary.pop(key)
  296. return value
  297. def MergeAndFilterByPlatform(env, params):
  298. """Take a dictionary of arguments to lists of values, and, depending on
  299. which platform we are targetting, merge the lists of associated keys.
  300. Merge by combining value lists like so:
  301. {win_foo = [a,b], lin_foo = [c,d], foo = [e], mac_bar = [f], bar = [g] }
  302. becomes {foo = [a,b,e], bar = [g]} on windows, and
  303. {foo = [e], bar = [f,g]} on mac
  304. Args:
  305. env: The hammer environment which knows which platforms are active
  306. params: The keyword argument dictionary.
  307. Returns:
  308. A new dictionary with the filtered and combined entries of params
  309. """
  310. platforms = {
  311. 'linux': 'lin_',
  312. 'mac': 'mac_',
  313. 'posix': 'posix_',
  314. 'windows': 'win_',
  315. }
  316. active_prefixes = [
  317. platforms[x] for x in iter(platforms) if env.Bit(x)
  318. ]
  319. inactive_prefixes = [
  320. platforms[x] for x in iter(platforms) if not env.Bit(x)
  321. ]
  322. merged = {}
  323. for arg, values in params.iteritems():
  324. inactive_platform = False
  325. key = arg
  326. for prefix in active_prefixes:
  327. if arg.startswith(prefix):
  328. key = arg[len(prefix):]
  329. for prefix in inactive_prefixes:
  330. if arg.startswith(prefix):
  331. inactive_platform = True
  332. if inactive_platform:
  333. continue
  334. AddToDict(merged, key, values)
  335. return merged
  336. def MergeSettingsFromLibraryDependencies(env, params):
  337. if 'libs' in params:
  338. for lib in params['libs']:
  339. libparams = _GetLibParams(env, lib)
  340. if libparams:
  341. if 'dependent_target_settings' in libparams:
  342. params = CombineDicts(
  343. params,
  344. MergeAndFilterByPlatform(
  345. env,
  346. libparams['dependent_target_settings']))
  347. return params
  348. def ExtendComponent(env, component, **kwargs):
  349. """A wrapper around a scons builder function that preprocesses and post-
  350. processes its inputs and outputs. For example, it merges and filters
  351. certain keyword arguments before appending them to the environments
  352. construction variables. It can build signed targets and 64bit copies
  353. of targets as well.
  354. Args:
  355. env: The hammer environment with which to build the target
  356. component: The environment's builder function, e.g. ComponentProgram
  357. kwargs: keyword arguments that are either merged, translated, and passed on
  358. to the call to component, or which control execution.
  359. TODO(): Document the fields, such as cppdefines->CPPDEFINES,
  360. prepend_includedirs, include_talk_media_libs, etc.
  361. Returns:
  362. The output node returned by the call to component, or a subsequent signed
  363. dependant node.
  364. """
  365. env = env.Clone()
  366. # prune parameters intended for other platforms, then merge
  367. params = MergeAndFilterByPlatform(env, kwargs)
  368. # get the 'target' field
  369. name = PopEntry(params, 'name')
  370. # get the 'packages' field and process it if present (only used for Linux).
  371. packages = PopEntry(params, 'packages')
  372. if packages and len(packages):
  373. params = CombineDicts(params, env.GetPackageParams(packages))
  374. # save pristine params of lib targets for future reference
  375. if 'ComponentLibrary' == component:
  376. _RecordLibParams(env, name, dict(params))
  377. # add any dependent target settings from library dependencies
  378. params = MergeSettingsFromLibraryDependencies(env, params)
  379. # if this is a signed binary we need to make an unsigned version first
  380. signed = env.Bit('windows') and PopEntry(params, 'signed')
  381. if signed:
  382. name = 'unsigned_' + name
  383. # potentially exit now
  384. srcs = PopEntry(params, 'srcs')
  385. if not srcs or not hasattr(env, component):
  386. return None
  387. # apply any explicit dependencies
  388. dependencies = PopEntry(params, 'depends')
  389. if dependencies is not None:
  390. env.Depends(name, dependencies)
  391. # put the contents of params into the environment
  392. # some entries are renamed then appended, others renamed then prepended
  393. appends = {
  394. 'cppdefines' : 'CPPDEFINES',
  395. 'libdirs' : 'LIBPATH',
  396. 'link_flags' : 'LINKFLAGS',
  397. 'libs' : 'LIBS',
  398. 'FRAMEWORKS' : 'FRAMEWORKS',
  399. }
  400. prepends = {}
  401. if env.Bit('windows'):
  402. # MSVC compile flags have precedence at the beginning ...
  403. prepends['ccflags'] = 'CCFLAGS'
  404. else:
  405. # ... while GCC compile flags have precedence at the end
  406. appends['ccflags'] = 'CCFLAGS'
  407. if PopEntry(params, 'prepend_includedirs'):
  408. prepends['includedirs'] = 'CPPPATH'
  409. else:
  410. appends['includedirs'] = 'CPPPATH'
  411. for field, var in appends.items():
  412. values = PopEntry(params, field)
  413. if values is not None:
  414. env.Append(**{var : values})
  415. for field, var in prepends.items():
  416. values = PopEntry(params, field)
  417. if values is not None:
  418. env.Prepend(**{var : values})
  419. # any other parameters are replaced without renaming
  420. for field, value in params.items():
  421. env.Replace(**{field : value})
  422. if env.Bit('linux') and 'LIBS' in env:
  423. libs = env['LIBS']
  424. # When using --as-needed + --start/end-group, shared libraries need to come
  425. # after --end-group on the command-line because the pruning decision only
  426. # considers the preceding modules and --start/end-group may cause the
  427. # effective position of early static libraries on the command-line to be
  428. # deferred to the point of --end-group. To effect this, we move shared libs
  429. # into _LIBFLAGS, which has the --end-group as its first entry. SCons does
  430. # not track dependencies on system shared libraries anyway so we lose
  431. # nothing by removing them from LIBS.
  432. static_libs = [lib for lib in libs if
  433. _GetLibParams(env, lib) or _IsPrebuiltLibrary(env, lib)]
  434. shared_libs = ['-l' + lib for lib in libs if not
  435. (_GetLibParams(env, lib) or _IsPrebuiltLibrary(env, lib))]
  436. env.Replace(LIBS=static_libs)
  437. env.Append(_LIBFLAGS=shared_libs)
  438. # invoke the builder function
  439. builder = getattr(env, component)
  440. node = builder(name, srcs)
  441. if env.Bit('mac') and 'ComponentProgram' == component:
  442. # Build .dSYM debug packages. This is useful even for non-stripped
  443. # binaries, as the dsym utility will fetch symbols from all
  444. # statically-linked libraries (the linker doesn't include them in to the
  445. # final binary).
  446. build_dsym = env.Command(
  447. env.Dir('$STAGING_DIR/%s.dSYM' % node[0]),
  448. node,
  449. 'mkdir -p `dirname $TARGET` && dsymutil -o $TARGET $SOURCE')
  450. env.Alias('all_dsym', env.Alias('%s.dSYM' % node[0], build_dsym))
  451. if signed:
  452. # Get the name of the built binary, then get the name of the final signed
  453. # version from it. We need the output path since we don't know the file
  454. # extension beforehand.
  455. target = node[0].path.split('_', 1)[1]
  456. # postsignprefix: If defined, postsignprefix is a string that should be
  457. # prepended to the target executable. This is to provide a work around
  458. # for EXEs and DLLs with the same name, which thus have PDBs with the
  459. # same name. Setting postsignprefix allows the EXE and its PDB
  460. # to be renamed and copied in a previous step; then the desired
  461. # name of the EXE (but not PDB) is reconstructed after signing.
  462. postsignprefix = PopEntry(params, 'postsignprefix')
  463. if postsignprefix is not None:
  464. target = postsignprefix + target
  465. signed_node = env.SignedBinary(
  466. source = node,
  467. target = '$STAGING_DIR/' + target,
  468. )
  469. env.Alias('signed_binaries', signed_node)
  470. return signed_node
  471. return node
  472. def AddToDict(dictionary, key, values, append=True):
  473. """Merge the given key value(s) pair into a dictionary. If it contains an
  474. entry with that key already, then combine by appending or prepending the
  475. values as directed. Otherwise, assign a new keyvalue pair.
  476. """
  477. if values is None:
  478. return
  479. if key not in dictionary:
  480. dictionary[key] = values
  481. return
  482. cur = dictionary[key]
  483. # TODO(dape): Make sure that there are no duplicates
  484. # in the list. I can't use python set for this since
  485. # the nodes that are returned by the SCONS builders
  486. # are not hashable.
  487. # dictionary[key] = list(set(cur).union(set(values)))
  488. if append:
  489. dictionary[key] = cur + values
  490. else:
  491. dictionary[key] = values + cur
  492. def CombineDicts(a, b):
  493. """Unions two dictionaries of arrays/dictionaries.
  494. Unions two dictionaries of arrays/dictionaries by combining the values of keys
  495. shared between them. The original dictionaries should not be used again after
  496. this call.
  497. Args:
  498. a: First dict.
  499. b: Second dict.
  500. Returns:
  501. The union of a and b.
  502. """
  503. c = {}
  504. for key in a:
  505. if key in b:
  506. aval = a[key]
  507. bval = b.pop(key)
  508. if isinstance(aval, dict) and isinstance(bval, dict):
  509. c[key] = CombineDicts(aval, bval)
  510. else:
  511. c[key] = aval + bval
  512. else:
  513. c[key] = a[key]
  514. for key in b:
  515. c[key] = b[key]
  516. return c
  517. def RenameKey(d, old, new, append=True):
  518. AddToDict(d, new, PopEntry(d, old), append)