ccroot.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Classes and methods shared by tools providing support for C-like language such
  6. as C/C++/D/Assembly/Go (this support module is almost never used alone).
  7. """
  8. import os, re
  9. from waflib import Task, Utils, Node, Errors, Logs
  10. from waflib.TaskGen import after_method, before_method, feature, taskgen_method, extension
  11. from waflib.Tools import c_aliases, c_preproc, c_config, c_osx, c_tests
  12. from waflib.Configure import conf
  13. SYSTEM_LIB_PATHS = ['/usr/lib64', '/usr/lib', '/usr/local/lib64', '/usr/local/lib']
  14. USELIB_VARS = Utils.defaultdict(set)
  15. """
  16. Mapping for features to :py:class:`waflib.ConfigSet.ConfigSet` variables. See :py:func:`waflib.Tools.ccroot.propagate_uselib_vars`.
  17. """
  18. USELIB_VARS['c'] = set(['INCLUDES', 'FRAMEWORKPATH', 'DEFINES', 'CPPFLAGS', 'CCDEPS', 'CFLAGS', 'ARCH'])
  19. USELIB_VARS['cxx'] = set(['INCLUDES', 'FRAMEWORKPATH', 'DEFINES', 'CPPFLAGS', 'CXXDEPS', 'CXXFLAGS', 'ARCH'])
  20. USELIB_VARS['d'] = set(['INCLUDES', 'DFLAGS'])
  21. USELIB_VARS['includes'] = set(['INCLUDES', 'FRAMEWORKPATH', 'ARCH'])
  22. USELIB_VARS['cprogram'] = USELIB_VARS['cxxprogram'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS', 'FRAMEWORK', 'FRAMEWORKPATH', 'ARCH', 'LDFLAGS'])
  23. USELIB_VARS['cshlib'] = USELIB_VARS['cxxshlib'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS', 'FRAMEWORK', 'FRAMEWORKPATH', 'ARCH', 'LDFLAGS'])
  24. USELIB_VARS['cstlib'] = USELIB_VARS['cxxstlib'] = set(['ARFLAGS', 'LINKDEPS'])
  25. USELIB_VARS['dprogram'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
  26. USELIB_VARS['dshlib'] = set(['LIB', 'STLIB', 'LIBPATH', 'STLIBPATH', 'LINKFLAGS', 'RPATH', 'LINKDEPS'])
  27. USELIB_VARS['dstlib'] = set(['ARFLAGS', 'LINKDEPS'])
  28. USELIB_VARS['asm'] = set(['ASFLAGS'])
  29. # =================================================================================================
  30. @taskgen_method
  31. def create_compiled_task(self, name, node):
  32. """
  33. Create the compilation task: c, cxx, asm, etc. The output node is created automatically (object file with a typical **.o** extension).
  34. The task is appended to the list *compiled_tasks* which is then used by :py:func:`waflib.Tools.ccroot.apply_link`
  35. :param name: name of the task class
  36. :type name: string
  37. :param node: the file to compile
  38. :type node: :py:class:`waflib.Node.Node`
  39. :return: The task created
  40. :rtype: :py:class:`waflib.Task.Task`
  41. """
  42. out = '%s.%d.o' % (node.name, self.idx)
  43. task = self.create_task(name, node, node.parent.find_or_declare(out))
  44. try:
  45. self.compiled_tasks.append(task)
  46. except AttributeError:
  47. self.compiled_tasks = [task]
  48. return task
  49. @taskgen_method
  50. def to_incnodes(self, inlst):
  51. """
  52. Task generator method provided to convert a list of string/nodes into a list of includes folders.
  53. The paths are assumed to be relative to the task generator path, except if they begin by **#**
  54. in which case they are searched from the top-level directory (``bld.srcnode``).
  55. The folders are simply assumed to be existing.
  56. The node objects in the list are returned in the output list. The strings are converted
  57. into node objects if possible. The node is searched from the source directory, and if a match is found,
  58. the equivalent build directory is created and added to the returned list too. When a folder cannot be found, it is ignored.
  59. :param inlst: list of folders
  60. :type inlst: space-delimited string or a list of string/nodes
  61. :rtype: list of :py:class:`waflib.Node.Node`
  62. :return: list of include folders as nodes
  63. """
  64. lst = []
  65. seen = set()
  66. for x in self.to_list(inlst):
  67. if x in seen or not x:
  68. continue
  69. seen.add(x)
  70. # with a real lot of targets, it is sometimes interesting to cache the results below
  71. if isinstance(x, Node.Node):
  72. lst.append(x)
  73. else:
  74. if os.path.isabs(x):
  75. lst.append(self.bld.root.make_node(x) or x)
  76. else:
  77. if x[0] == '#':
  78. p = self.bld.bldnode.make_node(x[1:])
  79. v = self.bld.srcnode.make_node(x[1:])
  80. else:
  81. p = self.path.get_bld().make_node(x)
  82. v = self.path.make_node(x)
  83. if p.is_child_of(self.bld.bldnode):
  84. p.mkdir()
  85. lst.append(p)
  86. lst.append(v)
  87. return lst
  88. @feature('c', 'cxx', 'd', 'asm', 'fc', 'includes')
  89. @after_method('propagate_uselib_vars', 'process_source')
  90. def apply_incpaths(self):
  91. """
  92. Task generator method that processes the attribute *includes*::
  93. tg = bld(features='includes', includes='.')
  94. The folders only need to be relative to the current directory, the equivalent build directory is
  95. added automatically (for headers created in the build directory). This enables using a build directory
  96. or not (``top == out``).
  97. This method will add a list of nodes read by :py:func:`waflib.Tools.ccroot.to_incnodes` in ``tg.env.INCPATHS``,
  98. and the list of include paths in ``tg.env.INCLUDES``.
  99. """
  100. lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env.INCLUDES)
  101. self.includes_nodes = lst
  102. cwd = self.get_cwd()
  103. if Utils.is_win32:
  104. # Visual Studio limitations
  105. self.env.INCPATHS = [x.path_from(cwd) if x.is_child_of(self.bld.srcnode) else x.abspath() for x in lst]
  106. else:
  107. self.env.INCPATHS = [x.path_from(cwd) for x in lst]
  108. class link_task(Task.Task):
  109. """
  110. Base class for all link tasks. A task generator is supposed to have at most one link task bound in the attribute *link_task*. See :py:func:`waflib.Tools.ccroot.apply_link`.
  111. .. inheritance-diagram:: waflib.Tools.ccroot.stlink_task waflib.Tools.c.cprogram waflib.Tools.c.cshlib waflib.Tools.cxx.cxxstlib waflib.Tools.cxx.cxxprogram waflib.Tools.cxx.cxxshlib waflib.Tools.d.dprogram waflib.Tools.d.dshlib waflib.Tools.d.dstlib waflib.Tools.ccroot.fake_shlib waflib.Tools.ccroot.fake_stlib waflib.Tools.asm.asmprogram waflib.Tools.asm.asmshlib waflib.Tools.asm.asmstlib
  112. :top-classes: waflib.Tools.ccroot.link_task
  113. """
  114. color = 'YELLOW'
  115. weight = 3
  116. """Try to process link tasks as early as possible"""
  117. inst_to = None
  118. """Default installation path for the link task outputs, or None to disable"""
  119. chmod = Utils.O755
  120. """Default installation mode for the link task outputs"""
  121. def add_target(self, target):
  122. """
  123. Process the *target* attribute to add the platform-specific prefix/suffix such as *.so* or *.exe*.
  124. The settings are retrieved from ``env.clsname_PATTERN``
  125. """
  126. if isinstance(target, str):
  127. base = self.generator.path
  128. if target.startswith('#'):
  129. # for those who like flat structures
  130. target = target[1:]
  131. base = self.generator.bld.bldnode
  132. pattern = self.env[self.__class__.__name__ + '_PATTERN']
  133. if not pattern:
  134. pattern = '%s'
  135. folder, name = os.path.split(target)
  136. if self.__class__.__name__.find('shlib') > 0 and getattr(self.generator, 'vnum', None):
  137. nums = self.generator.vnum.split('.')
  138. if self.env.DEST_BINFMT == 'pe':
  139. # include the version in the dll file name,
  140. # the import lib file name stays unversioned.
  141. name = name + '-' + nums[0]
  142. elif self.env.DEST_OS == 'openbsd':
  143. pattern = '%s.%s' % (pattern, nums[0])
  144. if len(nums) >= 2:
  145. pattern += '.%s' % nums[1]
  146. if folder:
  147. tmp = folder + os.sep + pattern % name
  148. else:
  149. tmp = pattern % name
  150. target = base.find_or_declare(tmp)
  151. self.set_outputs(target)
  152. def exec_command(self, *k, **kw):
  153. ret = super(link_task, self).exec_command(*k, **kw)
  154. if not ret and self.env.DO_MANIFEST:
  155. ret = self.exec_mf()
  156. return ret
  157. def exec_mf(self):
  158. """
  159. Create manifest files for VS-like compilers (msvc, ifort, ...)
  160. """
  161. if not self.env.MT:
  162. return 0
  163. manifest = None
  164. for out_node in self.outputs:
  165. if out_node.name.endswith('.manifest'):
  166. manifest = out_node.abspath()
  167. break
  168. else:
  169. # Should never get here. If we do, it means the manifest file was
  170. # never added to the outputs list, thus we don't have a manifest file
  171. # to embed, so we just return.
  172. return 0
  173. # embedding mode. Different for EXE's and DLL's.
  174. # see: http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx
  175. mode = ''
  176. for x in Utils.to_list(self.generator.features):
  177. if x in ('cprogram', 'cxxprogram', 'fcprogram', 'fcprogram_test'):
  178. mode = 1
  179. elif x in ('cshlib', 'cxxshlib', 'fcshlib'):
  180. mode = 2
  181. Logs.debug('msvc: embedding manifest in mode %r', mode)
  182. lst = [] + self.env.MT
  183. lst.extend(Utils.to_list(self.env.MTFLAGS))
  184. lst.extend(['-manifest', manifest])
  185. lst.append('-outputresource:%s;%s' % (self.outputs[0].abspath(), mode))
  186. return super(link_task, self).exec_command(lst)
  187. class stlink_task(link_task):
  188. """
  189. Base for static link tasks, which use *ar* most of the time.
  190. """
  191. run_str = [
  192. lambda task: task.remove_before_build(),
  193. '${AR} ${ARFLAGS} ${AR_TGT_F}${TGT} ${AR_SRC_F}${SRC}'
  194. ]
  195. chmod = Utils.O644
  196. """Default installation mode for the static libraries"""
  197. def remove_before_build(self):
  198. "Remove the library before building it"
  199. try:
  200. os.remove(self.outputs[0].abspath())
  201. except OSError:
  202. pass
  203. def rm_tgt(cls):
  204. # TODO obsolete code, remove in waf 2.2
  205. old = cls.run
  206. def wrap(self):
  207. try:
  208. os.remove(self.outputs[0].abspath())
  209. except OSError:
  210. pass
  211. return old(self)
  212. setattr(cls, 'run', wrap)
  213. @feature('skip_stlib_link_deps')
  214. @before_method('process_use')
  215. def apply_skip_stlib_link_deps(self):
  216. """
  217. This enables an optimization in the :py:func:wafilb.Tools.ccroot.processes_use: method that skips dependency and
  218. link flag optimizations for targets that generate static libraries (via the :py:class:Tools.ccroot.stlink_task task).
  219. The actual behavior is implemented in :py:func:wafilb.Tools.ccroot.processes_use: method so this feature only tells waf
  220. to enable the new behavior.
  221. """
  222. self.env.SKIP_STLIB_LINK_DEPS = True
  223. @feature('c', 'cxx', 'd', 'fc', 'asm')
  224. @after_method('process_source')
  225. def apply_link(self):
  226. """
  227. Collect the tasks stored in ``compiled_tasks`` (created by :py:func:`waflib.Tools.ccroot.create_compiled_task`), and
  228. use the outputs for a new instance of :py:class:`waflib.Tools.ccroot.link_task`. The class to use is the first link task
  229. matching a name from the attribute *features*, for example::
  230. def build(bld):
  231. tg = bld(features='cxx cxxprogram cprogram', source='main.c', target='app')
  232. will create the task ``tg.link_task`` as a new instance of :py:class:`waflib.Tools.cxx.cxxprogram`
  233. """
  234. for x in self.features:
  235. if x == 'cprogram' and 'cxx' in self.features: # limited compat
  236. x = 'cxxprogram'
  237. elif x == 'cshlib' and 'cxx' in self.features:
  238. x = 'cxxshlib'
  239. if x in Task.classes:
  240. if issubclass(Task.classes[x], link_task):
  241. link = x
  242. break
  243. else:
  244. return
  245. objs = [t.outputs[0] for t in getattr(self, 'compiled_tasks', [])]
  246. self.link_task = self.create_task(link, objs)
  247. self.link_task.add_target(self.target)
  248. # remember that the install paths are given by the task generators
  249. try:
  250. inst_to = self.install_path
  251. except AttributeError:
  252. inst_to = self.link_task.inst_to
  253. if inst_to:
  254. # install a copy of the node list we have at this moment (implib not added)
  255. self.install_task = self.add_install_files(
  256. install_to=inst_to, install_from=self.link_task.outputs[:],
  257. chmod=self.link_task.chmod, task=self.link_task)
  258. @taskgen_method
  259. def use_rec(self, name, **kw):
  260. """
  261. Processes the ``use`` keyword recursively. This method is kind of private and only meant to be used from ``process_use``
  262. """
  263. if name in self.tmp_use_not or name in self.tmp_use_seen:
  264. return
  265. try:
  266. y = self.bld.get_tgen_by_name(name)
  267. except Errors.WafError:
  268. self.uselib.append(name)
  269. self.tmp_use_not.add(name)
  270. return
  271. self.tmp_use_seen.append(name)
  272. y.post()
  273. # bind temporary attributes on the task generator
  274. y.tmp_use_objects = objects = kw.get('objects', True)
  275. y.tmp_use_stlib = stlib = kw.get('stlib', True)
  276. try:
  277. link_task = y.link_task
  278. except AttributeError:
  279. y.tmp_use_var = ''
  280. else:
  281. objects = False
  282. if not isinstance(link_task, stlink_task):
  283. stlib = False
  284. y.tmp_use_var = 'LIB'
  285. else:
  286. y.tmp_use_var = 'STLIB'
  287. p = self.tmp_use_prec
  288. for x in self.to_list(getattr(y, 'use', [])):
  289. if self.env["STLIB_" + x]:
  290. continue
  291. try:
  292. p[x].append(name)
  293. except KeyError:
  294. p[x] = [name]
  295. self.use_rec(x, objects=objects, stlib=stlib)
  296. @feature('c', 'cxx', 'd', 'use', 'fc')
  297. @before_method('apply_incpaths', 'propagate_uselib_vars')
  298. @after_method('apply_link', 'process_source')
  299. def process_use(self):
  300. """
  301. Process the ``use`` attribute which contains a list of task generator names::
  302. def build(bld):
  303. bld.shlib(source='a.c', target='lib1')
  304. bld.program(source='main.c', target='app', use='lib1')
  305. See :py:func:`waflib.Tools.ccroot.use_rec`.
  306. """
  307. use_not = self.tmp_use_not = set()
  308. self.tmp_use_seen = [] # we would like an ordered set
  309. use_prec = self.tmp_use_prec = {}
  310. self.uselib = self.to_list(getattr(self, 'uselib', []))
  311. self.includes = self.to_list(getattr(self, 'includes', []))
  312. names = self.to_list(getattr(self, 'use', []))
  313. for x in names:
  314. self.use_rec(x)
  315. for x in use_not:
  316. if x in use_prec:
  317. del use_prec[x]
  318. # topological sort
  319. out = self.tmp_use_sorted = []
  320. tmp = []
  321. for x in self.tmp_use_seen:
  322. for k in use_prec.values():
  323. if x in k:
  324. break
  325. else:
  326. tmp.append(x)
  327. while tmp:
  328. e = tmp.pop()
  329. out.append(e)
  330. try:
  331. nlst = use_prec[e]
  332. except KeyError:
  333. pass
  334. else:
  335. del use_prec[e]
  336. for x in nlst:
  337. for y in use_prec:
  338. if x in use_prec[y]:
  339. break
  340. else:
  341. tmp.append(x)
  342. if use_prec:
  343. raise Errors.WafError('Cycle detected in the use processing %r' % use_prec)
  344. out.reverse()
  345. link_task = getattr(self, 'link_task', None)
  346. for x in out:
  347. y = self.bld.get_tgen_by_name(x)
  348. var = y.tmp_use_var
  349. if var and link_task:
  350. if self.env.SKIP_STLIB_LINK_DEPS and isinstance(link_task, stlink_task):
  351. # If the skip_stlib_link_deps feature is enabled then we should
  352. # avoid adding lib deps to the stlink_task instance.
  353. pass
  354. elif var == 'LIB' or y.tmp_use_stlib or x in names:
  355. self.env.append_value(var, [y.target[y.target.rfind(os.sep) + 1:]])
  356. self.link_task.dep_nodes.extend(y.link_task.outputs)
  357. tmp_path = y.link_task.outputs[0].parent.path_from(self.get_cwd())
  358. self.env.append_unique(var + 'PATH', [tmp_path])
  359. else:
  360. if y.tmp_use_objects:
  361. self.add_objects_from_tgen(y)
  362. if getattr(y, 'export_includes', None):
  363. # self.includes may come from a global variable #2035
  364. self.includes = self.includes + y.to_incnodes(y.export_includes)
  365. if getattr(y, 'export_defines', None):
  366. self.env.append_value('DEFINES', self.to_list(y.export_defines))
  367. # and finally, add the use variables (no recursion needed)
  368. for x in names:
  369. try:
  370. y = self.bld.get_tgen_by_name(x)
  371. except Errors.WafError:
  372. if not self.env['STLIB_' + x] and not x in self.uselib:
  373. self.uselib.append(x)
  374. else:
  375. for k in self.to_list(getattr(y, 'use', [])):
  376. if not self.env['STLIB_' + k] and not k in self.uselib:
  377. self.uselib.append(k)
  378. @taskgen_method
  379. def accept_node_to_link(self, node):
  380. """
  381. PRIVATE INTERNAL USE ONLY
  382. """
  383. return not node.name.endswith('.pdb')
  384. @taskgen_method
  385. def add_objects_from_tgen(self, tg):
  386. """
  387. Add the objects from the depending compiled tasks as link task inputs.
  388. Some objects are filtered: for instance, .pdb files are added
  389. to the compiled tasks but not to the link tasks (to avoid errors)
  390. PRIVATE INTERNAL USE ONLY
  391. """
  392. try:
  393. link_task = self.link_task
  394. except AttributeError:
  395. pass
  396. else:
  397. for tsk in getattr(tg, 'compiled_tasks', []):
  398. for x in tsk.outputs:
  399. if self.accept_node_to_link(x):
  400. link_task.inputs.append(x)
  401. @taskgen_method
  402. def get_uselib_vars(self):
  403. """
  404. :return: the *uselib* variables associated to the *features* attribute (see :py:attr:`waflib.Tools.ccroot.USELIB_VARS`)
  405. :rtype: list of string
  406. """
  407. _vars = set()
  408. for x in self.features:
  409. if x in USELIB_VARS:
  410. _vars |= USELIB_VARS[x]
  411. return _vars
  412. @feature('c', 'cxx', 'd', 'fc', 'javac', 'cs', 'uselib', 'asm')
  413. @after_method('process_use')
  414. def propagate_uselib_vars(self):
  415. """
  416. Process uselib variables for adding flags. For example, the following target::
  417. def build(bld):
  418. bld.env.AFLAGS_aaa = ['bar']
  419. from waflib.Tools.ccroot import USELIB_VARS
  420. USELIB_VARS['aaa'] = ['AFLAGS']
  421. tg = bld(features='aaa', aflags='test')
  422. The *aflags* attribute will be processed and this method will set::
  423. tg.env.AFLAGS = ['bar', 'test']
  424. """
  425. _vars = self.get_uselib_vars()
  426. env = self.env
  427. app = env.append_value
  428. feature_uselib = self.features + self.to_list(getattr(self, 'uselib', []))
  429. for var in _vars:
  430. y = var.lower()
  431. val = getattr(self, y, [])
  432. if val:
  433. app(var, self.to_list(val))
  434. for x in feature_uselib:
  435. val = env['%s_%s' % (var, x)]
  436. if val:
  437. app(var, val)
  438. # ============ the code above must not know anything about import libs ==========
  439. @feature('cshlib', 'cxxshlib', 'fcshlib')
  440. @after_method('apply_link')
  441. def apply_implib(self):
  442. """
  443. Handle dlls and their import libs on Windows-like systems.
  444. A ``.dll.a`` file called *import library* is generated.
  445. It must be installed as it is required for linking the library.
  446. """
  447. if not self.env.DEST_BINFMT == 'pe':
  448. return
  449. dll = self.link_task.outputs[0]
  450. if isinstance(self.target, Node.Node):
  451. name = self.target.name
  452. else:
  453. name = os.path.split(self.target)[1]
  454. implib = self.env.implib_PATTERN % name
  455. implib = dll.parent.find_or_declare(implib)
  456. self.env.append_value('LINKFLAGS', self.env.IMPLIB_ST % implib.bldpath())
  457. self.link_task.outputs.append(implib)
  458. if getattr(self, 'defs', None) and self.env.DEST_BINFMT == 'pe':
  459. node = self.path.find_resource(self.defs)
  460. if not node:
  461. raise Errors.WafError('invalid def file %r' % self.defs)
  462. if self.env.def_PATTERN:
  463. self.env.append_value('LINKFLAGS', self.env.def_PATTERN % node.path_from(self.get_cwd()))
  464. self.link_task.dep_nodes.append(node)
  465. else:
  466. # gcc for windows takes *.def file as input without any special flag
  467. self.link_task.inputs.append(node)
  468. # where to put the import library
  469. if getattr(self, 'install_task', None):
  470. try:
  471. # user has given a specific installation path for the import library
  472. inst_to = self.install_path_implib
  473. except AttributeError:
  474. try:
  475. # user has given an installation path for the main library, put the import library in it
  476. inst_to = self.install_path
  477. except AttributeError:
  478. # else, put the library in BINDIR and the import library in LIBDIR
  479. inst_to = '${IMPLIBDIR}'
  480. self.install_task.install_to = '${BINDIR}'
  481. if not self.env.IMPLIBDIR:
  482. self.env.IMPLIBDIR = self.env.LIBDIR
  483. self.implib_install_task = self.add_install_files(install_to=inst_to, install_from=implib,
  484. chmod=self.link_task.chmod, task=self.link_task)
  485. # ============ the code above must not know anything about vnum processing on unix platforms =========
  486. re_vnum = re.compile('^([1-9]\\d*|0)([.]([1-9]\\d*|0)){0,2}?$')
  487. @feature('cshlib', 'cxxshlib', 'dshlib', 'fcshlib', 'vnum')
  488. @after_method('apply_link', 'propagate_uselib_vars')
  489. def apply_vnum(self):
  490. """
  491. Enforce version numbering on shared libraries. The valid version numbers must have either zero or two dots::
  492. def build(bld):
  493. bld.shlib(source='a.c', target='foo', vnum='14.15.16')
  494. In this example on Linux platform, ``libfoo.so`` is installed as ``libfoo.so.14.15.16``, and the following symbolic links are created:
  495. * ``libfoo.so → libfoo.so.14.15.16``
  496. * ``libfoo.so.14 → libfoo.so.14.15.16``
  497. By default, the library will be assigned SONAME ``libfoo.so.14``, effectively declaring ABI compatibility between all minor and patch releases for the major version of the library. When necessary, the compatibility can be explicitly defined using `cnum` parameter:
  498. def build(bld):
  499. bld.shlib(source='a.c', target='foo', vnum='14.15.16', cnum='14.15')
  500. In this case, the assigned SONAME will be ``libfoo.so.14.15`` with ABI compatibility only between path releases for a specific major and minor version of the library.
  501. On OS X platform, install-name parameter will follow the above logic for SONAME with exception that it also specifies an absolute path (based on install_path) of the library.
  502. """
  503. if not getattr(self, 'vnum', '') or os.name != 'posix' or self.env.DEST_BINFMT not in ('elf', 'mac-o'):
  504. return
  505. link = self.link_task
  506. if not re_vnum.match(self.vnum):
  507. raise Errors.WafError('Invalid vnum %r for target %r' % (self.vnum, getattr(self, 'name', self)))
  508. nums = self.vnum.split('.')
  509. node = link.outputs[0]
  510. cnum = getattr(self, 'cnum', str(nums[0]))
  511. cnums = cnum.split('.')
  512. if len(cnums)>len(nums) or nums[0:len(cnums)] != cnums:
  513. raise Errors.WafError('invalid compatibility version %s' % cnum)
  514. libname = node.name
  515. if libname.endswith('.dylib'):
  516. name3 = libname.replace('.dylib', '.%s.dylib' % self.vnum)
  517. name2 = libname.replace('.dylib', '.%s.dylib' % cnum)
  518. else:
  519. name3 = libname + '.' + self.vnum
  520. name2 = libname + '.' + cnum
  521. # add the so name for the ld linker - to disable, just unset env.SONAME_ST
  522. if self.env.SONAME_ST:
  523. v = self.env.SONAME_ST % name2
  524. self.env.append_value('LINKFLAGS', v.split())
  525. # the following task is just to enable execution from the build dir :-/
  526. if self.env.DEST_OS != 'openbsd':
  527. outs = [node.parent.make_node(name3)]
  528. if name2 != name3:
  529. outs.append(node.parent.make_node(name2))
  530. self.create_task('vnum', node, outs)
  531. if getattr(self, 'install_task', None):
  532. self.install_task.hasrun = Task.SKIPPED
  533. self.install_task.no_errcheck_out = True
  534. path = self.install_task.install_to
  535. if self.env.DEST_OS == 'openbsd':
  536. libname = self.link_task.outputs[0].name
  537. t1 = self.add_install_as(install_to='%s/%s' % (path, libname), install_from=node, chmod=self.link_task.chmod)
  538. self.vnum_install_task = (t1,)
  539. else:
  540. t1 = self.add_install_as(install_to=path + os.sep + name3, install_from=node, chmod=self.link_task.chmod)
  541. t3 = self.add_symlink_as(install_to=path + os.sep + libname, install_from=name3)
  542. if name2 != name3:
  543. t2 = self.add_symlink_as(install_to=path + os.sep + name2, install_from=name3)
  544. self.vnum_install_task = (t1, t2, t3)
  545. else:
  546. self.vnum_install_task = (t1, t3)
  547. if '-dynamiclib' in self.env.LINKFLAGS:
  548. # this requires after(propagate_uselib_vars)
  549. try:
  550. inst_to = self.install_path
  551. except AttributeError:
  552. inst_to = self.link_task.inst_to
  553. if inst_to:
  554. p = Utils.subst_vars(inst_to, self.env)
  555. path = os.path.join(p, name2)
  556. self.env.append_value('LINKFLAGS', ['-install_name', path])
  557. self.env.append_value('LINKFLAGS', '-Wl,-compatibility_version,%s' % cnum)
  558. self.env.append_value('LINKFLAGS', '-Wl,-current_version,%s' % self.vnum)
  559. class vnum(Task.Task):
  560. """
  561. Create the symbolic links for a versioned shared library. Instances are created by :py:func:`waflib.Tools.ccroot.apply_vnum`
  562. """
  563. color = 'CYAN'
  564. ext_in = ['.bin']
  565. def keyword(self):
  566. return 'Symlinking'
  567. def run(self):
  568. for x in self.outputs:
  569. path = x.abspath()
  570. try:
  571. os.remove(path)
  572. except OSError:
  573. pass
  574. try:
  575. os.symlink(self.inputs[0].name, path)
  576. except OSError:
  577. return 1
  578. class fake_shlib(link_task):
  579. """
  580. Task used for reading a system library and adding the dependency on it
  581. """
  582. def runnable_status(self):
  583. for t in self.run_after:
  584. if not t.hasrun:
  585. return Task.ASK_LATER
  586. return Task.SKIP_ME
  587. class fake_stlib(stlink_task):
  588. """
  589. Task used for reading a system library and adding the dependency on it
  590. """
  591. def runnable_status(self):
  592. for t in self.run_after:
  593. if not t.hasrun:
  594. return Task.ASK_LATER
  595. return Task.SKIP_ME
  596. @conf
  597. def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
  598. """
  599. Read a system shared library, enabling its use as a local library. Will trigger a rebuild if the file changes::
  600. def build(bld):
  601. bld.read_shlib('m')
  602. bld.program(source='main.c', use='m')
  603. """
  604. return self(name=name, features='fake_lib', lib_paths=paths, lib_type='shlib', export_includes=export_includes, export_defines=export_defines)
  605. @conf
  606. def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
  607. """
  608. Read a system static library, enabling a use as a local library. Will trigger a rebuild if the file changes.
  609. """
  610. return self(name=name, features='fake_lib', lib_paths=paths, lib_type='stlib', export_includes=export_includes, export_defines=export_defines)
  611. lib_patterns = {
  612. 'shlib' : ['lib%s.so', '%s.so', 'lib%s.dylib', 'lib%s.dll', '%s.dll'],
  613. 'stlib' : ['lib%s.a', '%s.a', 'lib%s.dll', '%s.dll', 'lib%s.lib', '%s.lib'],
  614. }
  615. @feature('fake_lib')
  616. def process_lib(self):
  617. """
  618. Find the location of a foreign library. Used by :py:class:`waflib.Tools.ccroot.read_shlib` and :py:class:`waflib.Tools.ccroot.read_stlib`.
  619. """
  620. node = None
  621. names = [x % self.name for x in lib_patterns[self.lib_type]]
  622. for x in self.lib_paths + [self.path] + SYSTEM_LIB_PATHS:
  623. if not isinstance(x, Node.Node):
  624. x = self.bld.root.find_node(x) or self.path.find_node(x)
  625. if not x:
  626. continue
  627. for y in names:
  628. node = x.find_node(y)
  629. if node:
  630. try:
  631. Utils.h_file(node.abspath())
  632. except EnvironmentError:
  633. raise ValueError('Could not read %r' % y)
  634. break
  635. else:
  636. continue
  637. break
  638. else:
  639. raise Errors.WafError('could not find library %r' % self.name)
  640. self.link_task = self.create_task('fake_%s' % self.lib_type, [], [node])
  641. self.target = self.name
  642. class fake_o(Task.Task):
  643. def runnable_status(self):
  644. return Task.SKIP_ME
  645. @extension('.o', '.obj')
  646. def add_those_o_files(self, node):
  647. tsk = self.create_task('fake_o', [], node)
  648. try:
  649. self.compiled_tasks.append(tsk)
  650. except AttributeError:
  651. self.compiled_tasks = [tsk]
  652. @feature('fake_obj')
  653. @before_method('process_source')
  654. def process_objs(self):
  655. """
  656. Puts object files in the task generator outputs
  657. """
  658. for node in self.to_nodes(self.source):
  659. self.add_those_o_files(node)
  660. self.source = []
  661. @conf
  662. def read_object(self, obj):
  663. """
  664. Read an object file, enabling injection in libs/programs. Will trigger a rebuild if the file changes.
  665. :param obj: object file path, as string or Node
  666. """
  667. if not isinstance(obj, self.path.__class__):
  668. obj = self.path.find_resource(obj)
  669. return self(features='fake_obj', source=obj, name=obj.name)
  670. @feature('cxxprogram', 'cprogram')
  671. @after_method('apply_link', 'process_use')
  672. def set_full_paths_hpux(self):
  673. """
  674. On hp-ux, extend the libpaths and static library paths to absolute paths
  675. """
  676. if self.env.DEST_OS != 'hp-ux':
  677. return
  678. base = self.bld.bldnode.abspath()
  679. for var in ['LIBPATH', 'STLIBPATH']:
  680. lst = []
  681. for x in self.env[var]:
  682. if x.startswith('/'):
  683. lst.append(x)
  684. else:
  685. lst.append(os.path.normpath(os.path.join(base, x)))
  686. self.env[var] = lst