gccdeps.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2008-2010 (ita)
  4. """
  5. Execute the tasks with gcc -MD, read the dependencies from the .d file
  6. and prepare the dependency calculation for the next run.
  7. This affects the cxx class, so make sure to load Qt5 after this tool.
  8. Usage::
  9. def options(opt):
  10. opt.load('compiler_cxx')
  11. def configure(conf):
  12. conf.load('compiler_cxx gccdeps')
  13. """
  14. import os, re, threading
  15. from waflib import Task, Logs, Utils, Errors
  16. from waflib.Tools import c_preproc
  17. from waflib.TaskGen import before_method, feature
  18. lock = threading.Lock()
  19. gccdeps_flags = ['-MD']
  20. if not c_preproc.go_absolute:
  21. gccdeps_flags = ['-MMD']
  22. # Third-party tools are allowed to add extra names in here with append()
  23. supported_compilers = ['gcc', 'icc', 'clang']
  24. def scan(self):
  25. if not self.__class__.__name__ in self.env.ENABLE_GCCDEPS:
  26. return super(self.derived_gccdeps, self).scan()
  27. nodes = self.generator.bld.node_deps.get(self.uid(), [])
  28. names = []
  29. return (nodes, names)
  30. re_o = re.compile("\.o$")
  31. re_splitter = re.compile(r'(?<!\\)\s+') # split by space, except when spaces are escaped
  32. def remove_makefile_rule_lhs(line):
  33. # Splitting on a plain colon would accidentally match inside a
  34. # Windows absolute-path filename, so we must search for a colon
  35. # followed by whitespace to find the divider between LHS and RHS
  36. # of the Makefile rule.
  37. rulesep = ': '
  38. sep_idx = line.find(rulesep)
  39. if sep_idx >= 0:
  40. return line[sep_idx + 2:]
  41. else:
  42. return line
  43. def path_to_node(base_node, path, cached_nodes):
  44. # Take the base node and the path and return a node
  45. # Results are cached because searching the node tree is expensive
  46. # The following code is executed by threads, it is not safe, so a lock is needed...
  47. if getattr(path, '__hash__'):
  48. node_lookup_key = (base_node, path)
  49. else:
  50. # Not hashable, assume it is a list and join into a string
  51. node_lookup_key = (base_node, os.path.sep.join(path))
  52. try:
  53. lock.acquire()
  54. node = cached_nodes[node_lookup_key]
  55. except KeyError:
  56. node = base_node.find_resource(path)
  57. cached_nodes[node_lookup_key] = node
  58. finally:
  59. lock.release()
  60. return node
  61. def post_run(self):
  62. if not self.__class__.__name__ in self.env.ENABLE_GCCDEPS:
  63. return super(self.derived_gccdeps, self).post_run()
  64. name = self.outputs[0].abspath()
  65. name = re_o.sub('.d', name)
  66. try:
  67. txt = Utils.readf(name)
  68. except EnvironmentError:
  69. Logs.error('Could not find a .d dependency file, are cflags/cxxflags overwritten?')
  70. raise
  71. #os.remove(name)
  72. # Compilers have the choice to either output the file's dependencies
  73. # as one large Makefile rule:
  74. #
  75. # /path/to/file.o: /path/to/dep1.h \
  76. # /path/to/dep2.h \
  77. # /path/to/dep3.h \
  78. # ...
  79. #
  80. # or as many individual rules:
  81. #
  82. # /path/to/file.o: /path/to/dep1.h
  83. # /path/to/file.o: /path/to/dep2.h
  84. # /path/to/file.o: /path/to/dep3.h
  85. # ...
  86. #
  87. # So the first step is to sanitize the input by stripping out the left-
  88. # hand side of all these lines. After that, whatever remains are the
  89. # implicit dependencies of task.outputs[0]
  90. txt = '\n'.join([remove_makefile_rule_lhs(line) for line in txt.splitlines()])
  91. # Now join all the lines together
  92. txt = txt.replace('\\\n', '')
  93. val = txt.strip()
  94. val = [x.replace('\\ ', ' ') for x in re_splitter.split(val) if x]
  95. nodes = []
  96. bld = self.generator.bld
  97. # Dynamically bind to the cache
  98. try:
  99. cached_nodes = bld.cached_nodes
  100. except AttributeError:
  101. cached_nodes = bld.cached_nodes = {}
  102. for x in val:
  103. node = None
  104. if os.path.isabs(x):
  105. node = path_to_node(bld.root, x, cached_nodes)
  106. else:
  107. # TODO waf 1.9 - single cwd value
  108. path = getattr(bld, 'cwdx', bld.bldnode)
  109. # when calling find_resource, make sure the path does not contain '..'
  110. x = [k for k in Utils.split_path(x) if k and k != '.']
  111. while '..' in x:
  112. idx = x.index('..')
  113. if idx == 0:
  114. x = x[1:]
  115. path = path.parent
  116. else:
  117. del x[idx]
  118. del x[idx-1]
  119. node = path_to_node(path, x, cached_nodes)
  120. if not node:
  121. continue
  122. if id(node) == id(self.inputs[0]):
  123. # ignore the source file, it is already in the dependencies
  124. # this way, successful config tests may be retrieved from the cache
  125. continue
  126. nodes.append(node)
  127. Logs.debug('deps: gccdeps for %s returned %s', self, nodes)
  128. bld.node_deps[self.uid()] = nodes
  129. bld.raw_deps[self.uid()] = []
  130. try:
  131. del self.cache_sig
  132. except AttributeError:
  133. pass
  134. Task.Task.post_run(self)
  135. def sig_implicit_deps(self):
  136. if not self.__class__.__name__ in self.env.ENABLE_GCCDEPS:
  137. return super(self.derived_gccdeps, self).sig_implicit_deps()
  138. try:
  139. return Task.Task.sig_implicit_deps(self)
  140. except Errors.WafError:
  141. return Utils.SIG_NIL
  142. def wrap_compiled_task(classname):
  143. derived_class = type(classname, (Task.classes[classname],), {})
  144. derived_class.derived_gccdeps = derived_class
  145. derived_class.post_run = post_run
  146. derived_class.scan = scan
  147. derived_class.sig_implicit_deps = sig_implicit_deps
  148. for k in ('c', 'cxx'):
  149. if k in Task.classes:
  150. wrap_compiled_task(k)
  151. @before_method('process_source')
  152. @feature('force_gccdeps')
  153. def force_gccdeps(self):
  154. self.env.ENABLE_GCCDEPS = ['c', 'cxx']
  155. def configure(conf):
  156. # in case someone provides a --enable-gccdeps command-line option
  157. if not getattr(conf.options, 'enable_gccdeps', True):
  158. return
  159. global gccdeps_flags
  160. flags = conf.env.GCCDEPS_FLAGS or gccdeps_flags
  161. if conf.env.CC_NAME in supported_compilers:
  162. try:
  163. conf.check(fragment='int main() { return 0; }', features='c force_gccdeps', cflags=flags, msg='Checking for c flags %r' % ''.join(flags))
  164. except Errors.ConfigurationError:
  165. pass
  166. else:
  167. conf.env.append_value('CFLAGS', gccdeps_flags)
  168. conf.env.append_unique('ENABLE_GCCDEPS', 'c')
  169. if conf.env.CXX_NAME in supported_compilers:
  170. try:
  171. conf.check(fragment='int main() { return 0; }', features='cxx force_gccdeps', cxxflags=flags, msg='Checking for cxx flags %r' % ''.join(flags))
  172. except Errors.ConfigurationError:
  173. pass
  174. else:
  175. conf.env.append_value('CXXFLAGS', gccdeps_flags)
  176. conf.env.append_unique('ENABLE_GCCDEPS', 'cxx')
  177. def options(opt):
  178. raise ValueError('Do not load gccdeps options')