jack2 codebase
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.

791 lines
26KB

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