2 # Copyright 2017 The Chromium Authors
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Find header files missing in GN.
8 This script gets all the header files from ninja_deps, which is from the true
9 dependency generated by the compiler, and report if they don't exist in GN.
20 from multiprocessing import Process, Queue
22 SRC_DIR = os.path.abspath(
23 os.path.join(os.path.abspath(os.path.dirname(__file__)), os.path.pardir))
24 DEPOT_TOOLS_DIR = os.path.join(SRC_DIR, 'third_party', 'depot_tools')
27 def GetHeadersFromNinja(out_dir, skip_obj, q):
28 """Return all the header files from ninja_deps"""
32 os.path.join(SRC_DIR, 'third_party', 'ninja', 'ninja'), '-C', out_dir,
35 # A negative bufsize means to use the system default, which usually
36 # means fully buffered.
37 popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=-1)
38 for line in iter(popen.stdout.readline, ''):
42 return_code = popen.wait()
44 raise subprocess.CalledProcessError(return_code, cmd)
46 ans, err = set(), None
48 ans = ParseNinjaDepsOutput(NinjaSource(), out_dir, skip_obj)
49 except Exception as e:
54 def ParseNinjaDepsOutput(ninja_out, out_dir, skip_obj):
55 """Parse ninja output and get the header files"""
58 # Ninja always uses "/", even on Windows.
63 for line in ninja_out:
64 if line.startswith(' '):
67 if line.endswith('.h') or line.endswith('.hh'):
69 if f.startswith(prefix):
70 f = f[6:] # Remove the '../../' prefix
71 # build/ only contains build-specific files like build_config.h
72 # and buildflag.h, and system header files, so they should be
74 if f.startswith(out_dir) or f.startswith('out'):
76 if not f.startswith('build'):
77 all_headers.setdefault(f, [])
79 all_headers[f].append(obj_file)
81 is_valid = line.endswith('(VALID)')
82 obj_file = line.split(':')[0]
87 def GetHeadersFromGN(out_dir, q):
88 """Return all the header files from GN"""
91 ans, err = set(), None
93 # Argument |dir| is needed to make sure it's on the same drive on Windows.
94 # dir='' means dir='.', but doesn't introduce an unneeded prefix.
95 tmp = tempfile.mkdtemp(dir='')
96 shutil.copy2(os.path.join(out_dir, 'args.gn'),
97 os.path.join(tmp, 'args.gn'))
98 # Do "gn gen" in a temp dir to prevent dirtying |out_dir|.
99 gn_exe = 'gn.bat' if sys.platform == 'win32' else 'gn'
100 subprocess.check_call([
101 os.path.join(DEPOT_TOOLS_DIR, gn_exe), 'gen', tmp, '--ide=json', '-q'])
102 gn_json = json.load(open(os.path.join(tmp, 'project.json')))
103 ans = ParseGNProjectJSON(gn_json, out_dir, tmp)
104 except Exception as e:
112 def ParseGNProjectJSON(gn, out_dir, tmp_out):
113 """Parse GN output and get the header files"""
116 for _target, properties in gn['targets'].items():
117 sources = properties.get('sources', [])
118 public = properties.get('public', [])
119 # Exclude '"public": "*"'.
120 if type(public) is list:
123 if f.endswith('.h') or f.endswith('.hh'):
124 if f.startswith('//'):
125 f = f[2:] # Strip the '//' prefix.
126 if f.startswith(tmp_out):
127 f = out_dir + f[len(tmp_out):]
133 def GetDepsPrefixes(q):
134 """Return all the folders controlled by DEPS file"""
135 prefixes, err = set(), None
137 gclient_exe = 'gclient.bat' if sys.platform == 'win32' else 'gclient'
138 gclient_out = subprocess.check_output([
139 os.path.join(DEPOT_TOOLS_DIR, gclient_exe),
140 'recurse', '--no-progress', '-j1',
141 'python', '-c', 'import os;print os.environ["GCLIENT_DEP_PATH"]'],
142 universal_newlines=True)
143 for i in gclient_out.split('\n'):
144 if i.startswith('src/'):
147 except Exception as e:
149 q.put((prefixes, err))
152 def IsBuildClean(out_dir):
153 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-n']
155 out = subprocess.check_output(cmd)
156 return 'no work to do.' in out
157 except Exception as e:
161 def ParseWhiteList(whitelist):
163 for line in whitelist.split('\n'):
164 line = re.sub(r'#.*', '', line).strip()
170 def FilterOutDepsedRepo(files, deps):
171 return {f for f in files if not any(f.startswith(d) for d in deps)}
174 def GetNonExistingFiles(lst):
177 if not os.path.isfile(f):
186 with open(args.json, 'w') as f:
193 parser = argparse.ArgumentParser(description='''
194 NOTE: Use ninja to build all targets in OUT_DIR before running
196 parser.add_argument('--out-dir', metavar='OUT_DIR', default='out/Release',
197 help='output directory of the build')
198 parser.add_argument('--json',
199 help='JSON output filename for missing headers')
200 parser.add_argument('--whitelist', help='file containing whitelist')
201 parser.add_argument('--skip-dirty-check', action='store_true',
202 help='skip checking whether the build is dirty')
203 parser.add_argument('--verbose', action='store_true',
204 help='print more diagnostic info')
206 args, _extras = parser.parse_known_args()
208 if not os.path.isdir(args.out_dir):
209 parser.error('OUT_DIR "%s" does not exist.' % args.out_dir)
211 if not args.skip_dirty_check and not IsBuildClean(args.out_dir):
212 dirty_msg = 'OUT_DIR looks dirty. You need to build all there.'
214 # Assume running on the bots. Silently skip this step.
215 # This is possible because "analyze" step can be wrong due to
216 # underspecified header files. See crbug.com/725877
221 # Assume running interactively.
222 parser.error(dirty_msg)
225 d_p = Process(target=GetHeadersFromNinja, args=(args.out_dir, True, d_q,))
229 gn_p = Process(target=GetHeadersFromGN, args=(args.out_dir, gn_q,))
233 deps_p = Process(target=GetDepsPrefixes, args=(deps_q,))
237 gn, gn_err = gn_q.get()
238 missing = set(d.keys()) - gn
239 nonexisting = GetNonExistingFiles(gn)
241 deps, deps_err = deps_q.get()
242 missing = FilterOutDepsedRepo(missing, deps)
243 nonexisting = FilterOutDepsedRepo(nonexisting, deps)
255 if len(GetNonExistingFiles(d)) > 0:
256 print('Non-existing files in ninja deps:', GetNonExistingFiles(d))
257 PrintError('Found non-existing files in ninja deps. You should ' +
258 'build all in OUT_DIR.')
260 PrintError('OUT_DIR looks empty. You should build all there.')
261 if any((('/gen/' in i) for i in nonexisting)):
262 PrintError('OUT_DIR looks wrong. You should build all there.')
265 whitelist = ParseWhiteList(open(args.whitelist).read())
267 nonexisting -= whitelist
269 missing = sorted(missing)
270 nonexisting = sorted(nonexisting)
272 DumpJson(sorted(missing + nonexisting))
274 if len(missing) == 0 and len(nonexisting) == 0:
278 print('\nThe following files should be included in gn files:')
282 if len(nonexisting) > 0:
283 print('\nThe following non-existing files should be removed from gn files:')
284 for i in nonexisting:
288 # Only get detailed obj dependency here since it is slower.
289 GetHeadersFromNinja(args.out_dir, False, d_q)
291 print('\nDetailed dependency info:')
297 print('\nMissing headers sorted by number of affected object files:')
298 count = {k: len(v) for (k, v) in d.items()}
299 for f in sorted(count, key=count.get, reverse=True):
304 # Assume running on the bots. Temporarily return 0 before
305 # https://crbug.com/937847 is fixed.
310 if __name__ == '__main__':