ccroot.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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 enable 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. self.env.INCPATHS = [x.path_from(cwd) for x in lst]
  104. class link_task(Task.Task):
  105. """
  106. 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`.
  107. .. 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
  108. """
  109. color = 'YELLOW'
  110. weight = 3
  111. """Try to process link tasks as early as possible"""
  112. inst_to = None
  113. """Default installation path for the link task outputs, or None to disable"""
  114. chmod = Utils.O755
  115. """Default installation mode for the link task outputs"""
  116. def add_target(self, target):
  117. """
  118. Process the *target* attribute to add the platform-specific prefix/suffix such as *.so* or *.exe*.
  119. The settings are retrieved from ``env.clsname_PATTERN``
  120. """
  121. if isinstance(target, str):
  122. base = self.generator.path
  123. if target.startswith('#'):
  124. # for those who like flat structures
  125. target = target[1:]
  126. base = self.generator.bld.bldnode
  127. pattern = self.env[self.__class__.__name__ + '_PATTERN']
  128. if not pattern:
  129. pattern = '%s'
  130. folder, name = os.path.split(target)
  131. if self.__class__.__name__.find('shlib') > 0 and getattr(self.generator, 'vnum', None):
  132. nums = self.generator.vnum.split('.')
  133. if self.env.DEST_BINFMT == 'pe':
  134. # include the version in the dll file name,
  135. # the import lib file name stays unversionned.
  136. name = name + '-' + nums[0]
  137. elif self.env.DEST_OS == 'openbsd':
  138. pattern = '%s.%s' % (pattern, nums[0])
  139. if len(nums) >= 2:
  140. pattern += '.%s' % nums[1]
  141. if folder:
  142. tmp = folder + os.sep + pattern % name
  143. else:
  144. tmp = pattern % name
  145. target = base.find_or_declare(tmp)
  146. self.set_outputs(target)
  147. def exec_command(self, *k, **kw):
  148. ret = super(link_task, self).exec_command(*k, **kw)
  149. if not ret and self.env.DO_MANIFEST:
  150. ret = self.exec_mf()
  151. return ret
  152. def exec_mf(self):
  153. """
  154. Create manifest files for VS-like compilers (msvc, ifort, ...)
  155. """
  156. if not self.env.MT:
  157. return 0
  158. manifest = None
  159. for out_node in self.outputs:
  160. if out_node.name.endswith('.manifest'):
  161. manifest = out_node.abspath()
  162. break
  163. else:
  164. # Should never get here. If we do, it means the manifest file was
  165. # never added to the outputs list, thus we don't have a manifest file
  166. # to embed, so we just return.
  167. return 0
  168. # embedding mode. Different for EXE's and DLL's.
  169. # see: http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx
  170. mode = ''
  171. for x in Utils.to_list(self.generator.features):
  172. if x in ('cprogram', 'cxxprogram', 'fcprogram', 'fcprogram_test'):
  173. mode = 1
  174. elif x in ('cshlib', 'cxxshlib', 'fcshlib'):
  175. mode = 2
  176. Logs.debug('msvc: embedding manifest in mode %r', mode)
  177. lst = [] + self.env.MT
  178. lst.extend(Utils.to_list(self.env.MTFLAGS))
  179. lst.extend(['-manifest', manifest])
  180. lst.append('-outputresource:%s;%s' % (self.outputs[0].abspath(), mode))
  181. return super(link_task, self).exec_command(lst)
  182. class stlink_task(link_task):
  183. """
  184. Base for static link tasks, which use *ar* most of the time.
  185. The target is always removed before being written.
  186. """
  187. run_str = '${AR} ${ARFLAGS} ${AR_TGT_F}${TGT} ${AR_SRC_F}${SRC}'
  188. chmod = Utils.O644
  189. """Default installation mode for the static libraries"""
  190. def rm_tgt(cls):
  191. old = cls.run
  192. def wrap(self):
  193. try:
  194. os.remove(self.outputs[0].abspath())
  195. except OSError:
  196. pass
  197. return old(self)
  198. setattr(cls, 'run', wrap)
  199. rm_tgt(stlink_task)
  200. @feature('c', 'cxx', 'd', 'fc', 'asm')
  201. @after_method('process_source')
  202. def apply_link(self):
  203. """
  204. Collect the tasks stored in ``compiled_tasks`` (created by :py:func:`waflib.Tools.ccroot.create_compiled_task`), and
  205. use the outputs for a new instance of :py:class:`waflib.Tools.ccroot.link_task`. The class to use is the first link task
  206. matching a name from the attribute *features*, for example::
  207. def build(bld):
  208. tg = bld(features='cxx cxxprogram cprogram', source='main.c', target='app')
  209. will create the task ``tg.link_task`` as a new instance of :py:class:`waflib.Tools.cxx.cxxprogram`
  210. """
  211. for x in self.features:
  212. if x == 'cprogram' and 'cxx' in self.features: # limited compat
  213. x = 'cxxprogram'
  214. elif x == 'cshlib' and 'cxx' in self.features:
  215. x = 'cxxshlib'
  216. if x in Task.classes:
  217. if issubclass(Task.classes[x], link_task):
  218. link = x
  219. break
  220. else:
  221. return
  222. objs = [t.outputs[0] for t in getattr(self, 'compiled_tasks', [])]
  223. self.link_task = self.create_task(link, objs)
  224. self.link_task.add_target(self.target)
  225. # remember that the install paths are given by the task generators
  226. try:
  227. inst_to = self.install_path
  228. except AttributeError:
  229. inst_to = self.link_task.inst_to
  230. if inst_to:
  231. # install a copy of the node list we have at this moment (implib not added)
  232. self.install_task = self.add_install_files(
  233. install_to=inst_to, install_from=self.link_task.outputs[:],
  234. chmod=self.link_task.chmod, task=self.link_task)
  235. @taskgen_method
  236. def use_rec(self, name, **kw):
  237. """
  238. Processes the ``use`` keyword recursively. This method is kind of private and only meant to be used from ``process_use``
  239. """
  240. if name in self.tmp_use_not or name in self.tmp_use_seen:
  241. return
  242. try:
  243. y = self.bld.get_tgen_by_name(name)
  244. except Errors.WafError:
  245. self.uselib.append(name)
  246. self.tmp_use_not.add(name)
  247. return
  248. self.tmp_use_seen.append(name)
  249. y.post()
  250. # bind temporary attributes on the task generator
  251. y.tmp_use_objects = objects = kw.get('objects', True)
  252. y.tmp_use_stlib = stlib = kw.get('stlib', True)
  253. try:
  254. link_task = y.link_task
  255. except AttributeError:
  256. y.tmp_use_var = ''
  257. else:
  258. objects = False
  259. if not isinstance(link_task, stlink_task):
  260. stlib = False
  261. y.tmp_use_var = 'LIB'
  262. else:
  263. y.tmp_use_var = 'STLIB'
  264. p = self.tmp_use_prec
  265. for x in self.to_list(getattr(y, 'use', [])):
  266. if self.env["STLIB_" + x]:
  267. continue
  268. try:
  269. p[x].append(name)
  270. except KeyError:
  271. p[x] = [name]
  272. self.use_rec(x, objects=objects, stlib=stlib)
  273. @feature('c', 'cxx', 'd', 'use', 'fc')
  274. @before_method('apply_incpaths', 'propagate_uselib_vars')
  275. @after_method('apply_link', 'process_source')
  276. def process_use(self):
  277. """
  278. Process the ``use`` attribute which contains a list of task generator names::
  279. def build(bld):
  280. bld.shlib(source='a.c', target='lib1')
  281. bld.program(source='main.c', target='app', use='lib1')
  282. See :py:func:`waflib.Tools.ccroot.use_rec`.
  283. """
  284. use_not = self.tmp_use_not = set()
  285. self.tmp_use_seen = [] # we would like an ordered set
  286. use_prec = self.tmp_use_prec = {}
  287. self.uselib = self.to_list(getattr(self, 'uselib', []))
  288. self.includes = self.to_list(getattr(self, 'includes', []))
  289. names = self.to_list(getattr(self, 'use', []))
  290. for x in names:
  291. self.use_rec(x)
  292. for x in use_not:
  293. if x in use_prec:
  294. del use_prec[x]
  295. # topological sort
  296. out = self.tmp_use_sorted = []
  297. tmp = []
  298. for x in self.tmp_use_seen:
  299. for k in use_prec.values():
  300. if x in k:
  301. break
  302. else:
  303. tmp.append(x)
  304. while tmp:
  305. e = tmp.pop()
  306. out.append(e)
  307. try:
  308. nlst = use_prec[e]
  309. except KeyError:
  310. pass
  311. else:
  312. del use_prec[e]
  313. for x in nlst:
  314. for y in use_prec:
  315. if x in use_prec[y]:
  316. break
  317. else:
  318. tmp.append(x)
  319. if use_prec:
  320. raise Errors.WafError('Cycle detected in the use processing %r' % use_prec)
  321. out.reverse()
  322. link_task = getattr(self, 'link_task', None)
  323. for x in out:
  324. y = self.bld.get_tgen_by_name(x)
  325. var = y.tmp_use_var
  326. if var and link_task:
  327. if var == 'LIB' or y.tmp_use_stlib or x in names:
  328. self.env.append_value(var, [y.target[y.target.rfind(os.sep) + 1:]])
  329. self.link_task.dep_nodes.extend(y.link_task.outputs)
  330. tmp_path = y.link_task.outputs[0].parent.path_from(self.get_cwd())
  331. self.env.append_unique(var + 'PATH', [tmp_path])
  332. else:
  333. if y.tmp_use_objects:
  334. self.add_objects_from_tgen(y)
  335. if getattr(y, 'export_includes', None):
  336. # self.includes may come from a global variable #2035
  337. self.includes = self.includes + y.to_incnodes(y.export_includes)
  338. if getattr(y, 'export_defines', None):
  339. self.env.append_value('DEFINES', self.to_list(y.export_defines))
  340. # and finally, add the use variables (no recursion needed)
  341. for x in names:
  342. try:
  343. y = self.bld.get_tgen_by_name(x)
  344. except Errors.WafError:
  345. if not self.env['STLIB_' + x] and not x in self.uselib:
  346. self.uselib.append(x)
  347. else:
  348. for k in self.to_list(getattr(y, 'use', [])):
  349. if not self.env['STLIB_' + k] and not k in self.uselib:
  350. self.uselib.append(k)
  351. @taskgen_method
  352. def accept_node_to_link(self, node):
  353. """
  354. PRIVATE INTERNAL USE ONLY
  355. """
  356. return not node.name.endswith('.pdb')
  357. @taskgen_method
  358. def add_objects_from_tgen(self, tg):
  359. """
  360. Add the objects from the depending compiled tasks as link task inputs.
  361. Some objects are filtered: for instance, .pdb files are added
  362. to the compiled tasks but not to the link tasks (to avoid errors)
  363. PRIVATE INTERNAL USE ONLY
  364. """
  365. try:
  366. link_task = self.link_task
  367. except AttributeError:
  368. pass
  369. else:
  370. for tsk in getattr(tg, 'compiled_tasks', []):
  371. for x in tsk.outputs:
  372. if self.accept_node_to_link(x):
  373. link_task.inputs.append(x)
  374. @taskgen_method
  375. def get_uselib_vars(self):
  376. """
  377. :return: the *uselib* variables associated to the *features* attribute (see :py:attr:`waflib.Tools.ccroot.USELIB_VARS`)
  378. :rtype: list of string
  379. """
  380. _vars = set()
  381. for x in self.features:
  382. if x in USELIB_VARS:
  383. _vars |= USELIB_VARS[x]
  384. return _vars
  385. @feature('c', 'cxx', 'd', 'fc', 'javac', 'cs', 'uselib', 'asm')
  386. @after_method('process_use')
  387. def propagate_uselib_vars(self):
  388. """
  389. Process uselib variables for adding flags. For example, the following target::
  390. def build(bld):
  391. bld.env.AFLAGS_aaa = ['bar']
  392. from waflib.Tools.ccroot import USELIB_VARS
  393. USELIB_VARS['aaa'] = ['AFLAGS']
  394. tg = bld(features='aaa', aflags='test')
  395. The *aflags* attribute will be processed and this method will set::
  396. tg.env.AFLAGS = ['bar', 'test']
  397. """
  398. _vars = self.get_uselib_vars()
  399. env = self.env
  400. app = env.append_value
  401. feature_uselib = self.features + self.to_list(getattr(self, 'uselib', []))
  402. for var in _vars:
  403. y = var.lower()
  404. val = getattr(self, y, [])
  405. if val:
  406. app(var, self.to_list(val))
  407. for x in feature_uselib:
  408. val = env['%s_%s' % (var, x)]
  409. if val:
  410. app(var, val)
  411. # ============ the code above must not know anything about import libs ==========
  412. @feature('cshlib', 'cxxshlib', 'fcshlib')
  413. @after_method('apply_link')
  414. def apply_implib(self):
  415. """
  416. Handle dlls and their import libs on Windows-like systems.
  417. A ``.dll.a`` file called *import library* is generated.
  418. It must be installed as it is required for linking the library.
  419. """
  420. if not self.env.DEST_BINFMT == 'pe':
  421. return
  422. dll = self.link_task.outputs[0]
  423. if isinstance(self.target, Node.Node):
  424. name = self.target.name
  425. else:
  426. name = os.path.split(self.target)[1]
  427. implib = self.env.implib_PATTERN % name
  428. implib = dll.parent.find_or_declare(implib)
  429. self.env.append_value('LINKFLAGS', self.env.IMPLIB_ST % implib.bldpath())
  430. self.link_task.outputs.append(implib)
  431. if getattr(self, 'defs', None) and self.env.DEST_BINFMT == 'pe':
  432. node = self.path.find_resource(self.defs)
  433. if not node:
  434. raise Errors.WafError('invalid def file %r' % self.defs)
  435. if self.env.def_PATTERN:
  436. self.env.append_value('LINKFLAGS', self.env.def_PATTERN % node.path_from(self.get_cwd()))
  437. self.link_task.dep_nodes.append(node)
  438. else:
  439. # gcc for windows takes *.def file as input without any special flag
  440. self.link_task.inputs.append(node)
  441. # where to put the import library
  442. if getattr(self, 'install_task', None):
  443. try:
  444. # user has given a specific installation path for the import library
  445. inst_to = self.install_path_implib
  446. except AttributeError:
  447. try:
  448. # user has given an installation path for the main library, put the import library in it
  449. inst_to = self.install_path
  450. except AttributeError:
  451. # else, put the library in BINDIR and the import library in LIBDIR
  452. inst_to = '${IMPLIBDIR}'
  453. self.install_task.install_to = '${BINDIR}'
  454. if not self.env.IMPLIBDIR:
  455. self.env.IMPLIBDIR = self.env.LIBDIR
  456. self.implib_install_task = self.add_install_files(install_to=inst_to, install_from=implib,
  457. chmod=self.link_task.chmod, task=self.link_task)
  458. # ============ the code above must not know anything about vnum processing on unix platforms =========
  459. re_vnum = re.compile('^([1-9]\\d*|0)([.]([1-9]\\d*|0)){0,2}?$')
  460. @feature('cshlib', 'cxxshlib', 'dshlib', 'fcshlib', 'vnum')
  461. @after_method('apply_link', 'propagate_uselib_vars')
  462. def apply_vnum(self):
  463. """
  464. Enforce version numbering on shared libraries. The valid version numbers must have either zero or two dots::
  465. def build(bld):
  466. bld.shlib(source='a.c', target='foo', vnum='14.15.16')
  467. In this example on Linux platform, ``libfoo.so`` is installed as ``libfoo.so.14.15.16``, and the following symbolic links are created:
  468. * ``libfoo.so → libfoo.so.14.15.16``
  469. * ``libfoo.so.14 → libfoo.so.14.15.16``
  470. 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:
  471. def build(bld):
  472. bld.shlib(source='a.c', target='foo', vnum='14.15.16', cnum='14.15')
  473. 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.
  474. 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.
  475. """
  476. if not getattr(self, 'vnum', '') or os.name != 'posix' or self.env.DEST_BINFMT not in ('elf', 'mac-o'):
  477. return
  478. link = self.link_task
  479. if not re_vnum.match(self.vnum):
  480. raise Errors.WafError('Invalid vnum %r for target %r' % (self.vnum, getattr(self, 'name', self)))
  481. nums = self.vnum.split('.')
  482. node = link.outputs[0]
  483. cnum = getattr(self, 'cnum', str(nums[0]))
  484. cnums = cnum.split('.')
  485. if len(cnums)>len(nums) or nums[0:len(cnums)] != cnums:
  486. raise Errors.WafError('invalid compatibility version %s' % cnum)
  487. libname = node.name
  488. if libname.endswith('.dylib'):
  489. name3 = libname.replace('.dylib', '.%s.dylib' % self.vnum)
  490. name2 = libname.replace('.dylib', '.%s.dylib' % cnum)
  491. else:
  492. name3 = libname + '.' + self.vnum
  493. name2 = libname + '.' + cnum
  494. # add the so name for the ld linker - to disable, just unset env.SONAME_ST
  495. if self.env.SONAME_ST:
  496. v = self.env.SONAME_ST % name2
  497. self.env.append_value('LINKFLAGS', v.split())
  498. # the following task is just to enable execution from the build dir :-/
  499. if self.env.DEST_OS != 'openbsd':
  500. outs = [node.parent.make_node(name3)]
  501. if name2 != name3:
  502. outs.append(node.parent.make_node(name2))
  503. self.create_task('vnum', node, outs)
  504. if getattr(self, 'install_task', None):
  505. self.install_task.hasrun = Task.SKIPPED
  506. path = self.install_task.install_to
  507. if self.env.DEST_OS == 'openbsd':
  508. libname = self.link_task.outputs[0].name
  509. t1 = self.add_install_as(install_to='%s/%s' % (path, libname), install_from=node, chmod=self.link_task.chmod)
  510. self.vnum_install_task = (t1,)
  511. else:
  512. t1 = self.add_install_as(install_to=path + os.sep + name3, install_from=node, chmod=self.link_task.chmod)
  513. t3 = self.add_symlink_as(install_to=path + os.sep + libname, install_from=name3)
  514. if name2 != name3:
  515. t2 = self.add_symlink_as(install_to=path + os.sep + name2, install_from=name3)
  516. self.vnum_install_task = (t1, t2, t3)
  517. else:
  518. self.vnum_install_task = (t1, t3)
  519. if '-dynamiclib' in self.env.LINKFLAGS:
  520. # this requires after(propagate_uselib_vars)
  521. try:
  522. inst_to = self.install_path
  523. except AttributeError:
  524. inst_to = self.link_task.inst_to
  525. if inst_to:
  526. p = Utils.subst_vars(inst_to, self.env)
  527. path = os.path.join(p, name2)
  528. self.env.append_value('LINKFLAGS', ['-install_name', path])
  529. self.env.append_value('LINKFLAGS', '-Wl,-compatibility_version,%s' % cnum)
  530. self.env.append_value('LINKFLAGS', '-Wl,-current_version,%s' % self.vnum)
  531. class vnum(Task.Task):
  532. """
  533. Create the symbolic links for a versioned shared library. Instances are created by :py:func:`waflib.Tools.ccroot.apply_vnum`
  534. """
  535. color = 'CYAN'
  536. ext_in = ['.bin']
  537. def keyword(self):
  538. return 'Symlinking'
  539. def run(self):
  540. for x in self.outputs:
  541. path = x.abspath()
  542. try:
  543. os.remove(path)
  544. except OSError:
  545. pass
  546. try:
  547. os.symlink(self.inputs[0].name, path)
  548. except OSError:
  549. return 1
  550. class fake_shlib(link_task):
  551. """
  552. Task used for reading a system library and adding the dependency on it
  553. """
  554. def runnable_status(self):
  555. for t in self.run_after:
  556. if not t.hasrun:
  557. return Task.ASK_LATER
  558. return Task.SKIP_ME
  559. class fake_stlib(stlink_task):
  560. """
  561. Task used for reading a system library and adding the dependency on it
  562. """
  563. def runnable_status(self):
  564. for t in self.run_after:
  565. if not t.hasrun:
  566. return Task.ASK_LATER
  567. return Task.SKIP_ME
  568. @conf
  569. def read_shlib(self, name, paths=[], export_includes=[], export_defines=[]):
  570. """
  571. Read a system shared library, enabling its use as a local library. Will trigger a rebuild if the file changes::
  572. def build(bld):
  573. bld.read_shlib('m')
  574. bld.program(source='main.c', use='m')
  575. """
  576. return self(name=name, features='fake_lib', lib_paths=paths, lib_type='shlib', export_includes=export_includes, export_defines=export_defines)
  577. @conf
  578. def read_stlib(self, name, paths=[], export_includes=[], export_defines=[]):
  579. """
  580. Read a system static library, enabling a use as a local library. Will trigger a rebuild if the file changes.
  581. """
  582. return self(name=name, features='fake_lib', lib_paths=paths, lib_type='stlib', export_includes=export_includes, export_defines=export_defines)
  583. lib_patterns = {
  584. 'shlib' : ['lib%s.so', '%s.so', 'lib%s.dylib', 'lib%s.dll', '%s.dll'],
  585. 'stlib' : ['lib%s.a', '%s.a', 'lib%s.dll', '%s.dll', 'lib%s.lib', '%s.lib'],
  586. }
  587. @feature('fake_lib')
  588. def process_lib(self):
  589. """
  590. Find the location of a foreign library. Used by :py:class:`waflib.Tools.ccroot.read_shlib` and :py:class:`waflib.Tools.ccroot.read_stlib`.
  591. """
  592. node = None
  593. names = [x % self.name for x in lib_patterns[self.lib_type]]
  594. for x in self.lib_paths + [self.path] + SYSTEM_LIB_PATHS:
  595. if not isinstance(x, Node.Node):
  596. x = self.bld.root.find_node(x) or self.path.find_node(x)
  597. if not x:
  598. continue
  599. for y in names:
  600. node = x.find_node(y)
  601. if node:
  602. try:
  603. Utils.h_file(node.abspath())
  604. except EnvironmentError:
  605. raise ValueError('Could not read %r' % y)
  606. break
  607. else:
  608. continue
  609. break
  610. else:
  611. raise Errors.WafError('could not find library %r' % self.name)
  612. self.link_task = self.create_task('fake_%s' % self.lib_type, [], [node])
  613. self.target = self.name
  614. class fake_o(Task.Task):
  615. def runnable_status(self):
  616. return Task.SKIP_ME
  617. @extension('.o', '.obj')
  618. def add_those_o_files(self, node):
  619. tsk = self.create_task('fake_o', [], node)
  620. try:
  621. self.compiled_tasks.append(tsk)
  622. except AttributeError:
  623. self.compiled_tasks = [tsk]
  624. @feature('fake_obj')
  625. @before_method('process_source')
  626. def process_objs(self):
  627. """
  628. Puts object files in the task generator outputs
  629. """
  630. for node in self.to_nodes(self.source):
  631. self.add_those_o_files(node)
  632. self.source = []
  633. @conf
  634. def read_object(self, obj):
  635. """
  636. Read an object file, enabling injection in libs/programs. Will trigger a rebuild if the file changes.
  637. :param obj: object file path, as string or Node
  638. """
  639. if not isinstance(obj, self.path.__class__):
  640. obj = self.path.find_resource(obj)
  641. return self(features='fake_obj', source=obj, name=obj.name)
  642. @feature('cxxprogram', 'cprogram')
  643. @after_method('apply_link', 'process_use')
  644. def set_full_paths_hpux(self):
  645. """
  646. On hp-ux, extend the libpaths and static library paths to absolute paths
  647. """
  648. if self.env.DEST_OS != 'hp-ux':
  649. return
  650. base = self.bld.bldnode.abspath()
  651. for var in ['LIBPATH', 'STLIBPATH']:
  652. lst = []
  653. for x in self.env[var]:
  654. if x.startswith('/'):
  655. lst.append(x)
  656. else:
  657. lst.append(os.path.normpath(os.path.join(base, x)))
  658. self.env[var] = lst