blob: 9bdbba895f090508b24c2cc1766ed661546a6c4c [file] [log] [blame]
wychen037f6e9e2017-01-10 17:14:561#!/usr/bin/env python
2# Copyright 2017 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Find header files missing in GN.
7
8This script gets all the header files from ninja_deps, which is from the true
9dependency generated by the compiler, and report if they don't exist in GN.
10"""
11
Raul Tambre9e24293b2019-05-12 06:11:0712from __future__ import print_function
13
wychen037f6e9e2017-01-10 17:14:5614import argparse
15import json
16import os
17import re
wychen03629112017-05-25 20:37:1818import shutil
wychen037f6e9e2017-01-10 17:14:5619import subprocess
20import sys
wychen03629112017-05-25 20:37:1821import tempfile
wychenef74ec992017-04-27 06:28:2522from multiprocessing import Process, Queue
wychen037f6e9e2017-01-10 17:14:5623
nodir6a40e9402017-06-07 05:49:0324SRC_DIR = os.path.abspath(
25 os.path.join(os.path.abspath(os.path.dirname(__file__)), os.path.pardir))
26DEPOT_TOOLS_DIR = os.path.join(SRC_DIR, 'third_party', 'depot_tools')
27
wychen037f6e9e2017-01-10 17:14:5628
wychen8cc31232017-06-13 10:21:2329def GetHeadersFromNinja(out_dir, skip_obj, q):
wychen037f6e9e2017-01-10 17:14:5630 """Return all the header files from ninja_deps"""
wychenef74ec992017-04-27 06:28:2531
32 def NinjaSource():
nodir6a40e9402017-06-07 05:49:0333 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-t', 'deps']
wychenef74ec992017-04-27 06:28:2534 # A negative bufsize means to use the system default, which usually
35 # means fully buffered.
36 popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=-1)
37 for line in iter(popen.stdout.readline, ''):
38 yield line.rstrip()
39
40 popen.stdout.close()
41 return_code = popen.wait()
42 if return_code:
43 raise subprocess.CalledProcessError(return_code, cmd)
44
wychen09692cd2017-05-26 01:57:1645 ans, err = set(), None
46 try:
wychen8cc31232017-06-13 10:21:2347 ans = ParseNinjaDepsOutput(NinjaSource(), out_dir, skip_obj)
wychen09692cd2017-05-26 01:57:1648 except Exception as e:
49 err = str(e)
50 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:5651
52
wychen8cc31232017-06-13 10:21:2353def ParseNinjaDepsOutput(ninja_out, out_dir, skip_obj):
wychen037f6e9e2017-01-10 17:14:5654 """Parse ninja output and get the header files"""
wychen8cc31232017-06-13 10:21:2355 all_headers = {}
wychen037f6e9e2017-01-10 17:14:5656
wychen97580de2017-06-13 00:52:4457 # Ninja always uses "/", even on Windows.
58 prefix = '../../'
wychen037f6e9e2017-01-10 17:14:5659
60 is_valid = False
wychen8cc31232017-06-13 10:21:2361 obj_file = ''
wychenef74ec992017-04-27 06:28:2562 for line in ninja_out:
wychen037f6e9e2017-01-10 17:14:5663 if line.startswith(' '):
64 if not is_valid:
65 continue
66 if line.endswith('.h') or line.endswith('.hh'):
67 f = line.strip()
68 if f.startswith(prefix):
69 f = f[6:] # Remove the '../../' prefix
70 # build/ only contains build-specific files like build_config.h
71 # and buildflag.h, and system header files, so they should be
72 # skipped.
wychen0735fd762017-06-03 07:53:2673 if f.startswith(out_dir) or f.startswith('out'):
74 continue
wychen037f6e9e2017-01-10 17:14:5675 if not f.startswith('build'):
wychen8cc31232017-06-13 10:21:2376 all_headers.setdefault(f, [])
77 if not skip_obj:
78 all_headers[f].append(obj_file)
wychen037f6e9e2017-01-10 17:14:5679 else:
80 is_valid = line.endswith('(VALID)')
wychen8cc31232017-06-13 10:21:2381 obj_file = line.split(':')[0]
wychen037f6e9e2017-01-10 17:14:5682
83 return all_headers
84
85
wychenef74ec992017-04-27 06:28:2586def GetHeadersFromGN(out_dir, q):
wychen037f6e9e2017-01-10 17:14:5687 """Return all the header files from GN"""
wychen03629112017-05-25 20:37:1888
89 tmp = None
wychen09692cd2017-05-26 01:57:1690 ans, err = set(), None
wychen03629112017-05-25 20:37:1891 try:
wychen97580de2017-06-13 00:52:4492 # Argument |dir| is needed to make sure it's on the same drive on Windows.
93 # dir='' means dir='.', but doesn't introduce an unneeded prefix.
94 tmp = tempfile.mkdtemp(dir='')
wychen03629112017-05-25 20:37:1895 shutil.copy2(os.path.join(out_dir, 'args.gn'),
96 os.path.join(tmp, 'args.gn'))
97 # Do "gn gen" in a temp dir to prevent dirtying |out_dir|.
wychen97580de2017-06-13 00:52:4498 gn_exe = 'gn.bat' if sys.platform == 'win32' else 'gn'
nodir6a40e9402017-06-07 05:49:0399 subprocess.check_call([
wychen8cc31232017-06-13 10:21:23100 os.path.join(DEPOT_TOOLS_DIR, gn_exe), 'gen', tmp, '--ide=json', '-q'])
wychen03629112017-05-25 20:37:18101 gn_json = json.load(open(os.path.join(tmp, 'project.json')))
wychen09692cd2017-05-26 01:57:16102 ans = ParseGNProjectJSON(gn_json, out_dir, tmp)
103 except Exception as e:
104 err = str(e)
wychen03629112017-05-25 20:37:18105 finally:
106 if tmp:
107 shutil.rmtree(tmp)
wychen09692cd2017-05-26 01:57:16108 q.put((ans, err))
wychen037f6e9e2017-01-10 17:14:56109
110
wychen03629112017-05-25 20:37:18111def ParseGNProjectJSON(gn, out_dir, tmp_out):
wychen037f6e9e2017-01-10 17:14:56112 """Parse GN output and get the header files"""
113 all_headers = set()
114
115 for _target, properties in gn['targets'].iteritems():
wychen55235782017-04-28 01:59:15116 sources = properties.get('sources', [])
117 public = properties.get('public', [])
118 # Exclude '"public": "*"'.
119 if type(public) is list:
120 sources += public
121 for f in sources:
wychen037f6e9e2017-01-10 17:14:56122 if f.endswith('.h') or f.endswith('.hh'):
123 if f.startswith('//'):
124 f = f[2:] # Strip the '//' prefix.
wychen03629112017-05-25 20:37:18125 if f.startswith(tmp_out):
126 f = out_dir + f[len(tmp_out):]
wychen037f6e9e2017-01-10 17:14:56127 all_headers.add(f)
128
129 return all_headers
130
131
wychenef74ec992017-04-27 06:28:25132def GetDepsPrefixes(q):
wychen037f6e9e2017-01-10 17:14:56133 """Return all the folders controlled by DEPS file"""
wychen09692cd2017-05-26 01:57:16134 prefixes, err = set(), None
135 try:
wychen97580de2017-06-13 00:52:44136 gclient_exe = 'gclient.bat' if sys.platform == 'win32' else 'gclient'
nodir6a40e9402017-06-07 05:49:03137 gclient_out = subprocess.check_output([
wychen97580de2017-06-13 00:52:44138 os.path.join(DEPOT_TOOLS_DIR, gclient_exe),
139 'recurse', '--no-progress', '-j1',
140 'python', '-c', 'import os;print os.environ["GCLIENT_DEP_PATH"]'],
141 universal_newlines=True)
wychen09692cd2017-05-26 01:57:16142 for i in gclient_out.split('\n'):
143 if i.startswith('src/'):
144 i = i[4:]
145 prefixes.add(i)
146 except Exception as e:
147 err = str(e)
148 q.put((prefixes, err))
wychen037f6e9e2017-01-10 17:14:56149
150
wychen0735fd762017-06-03 07:53:26151def IsBuildClean(out_dir):
nodir6a40e9402017-06-07 05:49:03152 cmd = [os.path.join(DEPOT_TOOLS_DIR, 'ninja'), '-C', out_dir, '-n']
wychen67aabe02017-06-17 00:12:04153 try:
154 out = subprocess.check_output(cmd)
155 return 'no work to do.' in out
156 except Exception as e:
Raul Tambre9e24293b2019-05-12 06:11:07157 print(e)
wychen67aabe02017-06-17 00:12:04158 return False
wychen0735fd762017-06-03 07:53:26159
wychen037f6e9e2017-01-10 17:14:56160def ParseWhiteList(whitelist):
161 out = set()
162 for line in whitelist.split('\n'):
163 line = re.sub(r'#.*', '', line).strip()
164 if line:
165 out.add(line)
166 return out
167
168
wychene7a3d6482017-04-29 07:12:17169def FilterOutDepsedRepo(files, deps):
170 return {f for f in files if not any(f.startswith(d) for d in deps)}
171
172
173def GetNonExistingFiles(lst):
174 out = set()
175 for f in lst:
176 if not os.path.isfile(f):
177 out.add(f)
178 return out
179
180
wychen037f6e9e2017-01-10 17:14:56181def main():
wychen0735fd762017-06-03 07:53:26182
183 def DumpJson(data):
184 if args.json:
185 with open(args.json, 'w') as f:
186 json.dump(data, f)
187
188 def PrintError(msg):
189 DumpJson([])
190 parser.error(msg)
191
wychen03629112017-05-25 20:37:18192 parser = argparse.ArgumentParser(description='''
193 NOTE: Use ninja to build all targets in OUT_DIR before running
194 this script.''')
195 parser.add_argument('--out-dir', metavar='OUT_DIR', default='out/Release',
196 help='output directory of the build')
197 parser.add_argument('--json',
198 help='JSON output filename for missing headers')
199 parser.add_argument('--whitelist', help='file containing whitelist')
wychen0735fd762017-06-03 07:53:26200 parser.add_argument('--skip-dirty-check', action='store_true',
201 help='skip checking whether the build is dirty')
wychen8cc31232017-06-13 10:21:23202 parser.add_argument('--verbose', action='store_true',
203 help='print more diagnostic info')
wychen037f6e9e2017-01-10 17:14:56204
205 args, _extras = parser.parse_known_args()
206
wychen03629112017-05-25 20:37:18207 if not os.path.isdir(args.out_dir):
208 parser.error('OUT_DIR "%s" does not exist.' % args.out_dir)
209
wychen0735fd762017-06-03 07:53:26210 if not args.skip_dirty_check and not IsBuildClean(args.out_dir):
211 dirty_msg = 'OUT_DIR looks dirty. You need to build all there.'
212 if args.json:
213 # Assume running on the bots. Silently skip this step.
214 # This is possible because "analyze" step can be wrong due to
215 # underspecified header files. See crbug.com/725877
Raul Tambre9e24293b2019-05-12 06:11:07216 print(dirty_msg)
wychen0735fd762017-06-03 07:53:26217 DumpJson([])
218 return 0
219 else:
220 # Assume running interactively.
221 parser.error(dirty_msg)
222
wychenef74ec992017-04-27 06:28:25223 d_q = Queue()
wychen8cc31232017-06-13 10:21:23224 d_p = Process(target=GetHeadersFromNinja, args=(args.out_dir, True, d_q,))
wychenef74ec992017-04-27 06:28:25225 d_p.start()
226
227 gn_q = Queue()
228 gn_p = Process(target=GetHeadersFromGN, args=(args.out_dir, gn_q,))
229 gn_p.start()
230
231 deps_q = Queue()
232 deps_p = Process(target=GetDepsPrefixes, args=(deps_q,))
233 deps_p.start()
234
wychen09692cd2017-05-26 01:57:16235 d, d_err = d_q.get()
236 gn, gn_err = gn_q.get()
wychen8cc31232017-06-13 10:21:23237 missing = set(d.keys()) - gn
wychene7a3d6482017-04-29 07:12:17238 nonexisting = GetNonExistingFiles(gn)
wychen037f6e9e2017-01-10 17:14:56239
wychen09692cd2017-05-26 01:57:16240 deps, deps_err = deps_q.get()
wychene7a3d6482017-04-29 07:12:17241 missing = FilterOutDepsedRepo(missing, deps)
242 nonexisting = FilterOutDepsedRepo(nonexisting, deps)
wychen037f6e9e2017-01-10 17:14:56243
wychenef74ec992017-04-27 06:28:25244 d_p.join()
245 gn_p.join()
246 deps_p.join()
247
wychen09692cd2017-05-26 01:57:16248 if d_err:
wychen0735fd762017-06-03 07:53:26249 PrintError(d_err)
wychen09692cd2017-05-26 01:57:16250 if gn_err:
wychen0735fd762017-06-03 07:53:26251 PrintError(gn_err)
wychen09692cd2017-05-26 01:57:16252 if deps_err:
wychen0735fd762017-06-03 07:53:26253 PrintError(deps_err)
wychen03629112017-05-25 20:37:18254 if len(GetNonExistingFiles(d)) > 0:
Raul Tambre9e24293b2019-05-12 06:11:07255 print('Non-existing files in ninja deps:', GetNonExistingFiles(d))
wychen0735fd762017-06-03 07:53:26256 PrintError('Found non-existing files in ninja deps. You should ' +
257 'build all in OUT_DIR.')
wychen03629112017-05-25 20:37:18258 if len(d) == 0:
wychen0735fd762017-06-03 07:53:26259 PrintError('OUT_DIR looks empty. You should build all there.')
wychen03629112017-05-25 20:37:18260 if any((('/gen/' in i) for i in nonexisting)):
wychen0735fd762017-06-03 07:53:26261 PrintError('OUT_DIR looks wrong. You should build all there.')
wychen03629112017-05-25 20:37:18262
wychen037f6e9e2017-01-10 17:14:56263 if args.whitelist:
264 whitelist = ParseWhiteList(open(args.whitelist).read())
265 missing -= whitelist
wychen0735fd762017-06-03 07:53:26266 nonexisting -= whitelist
wychen037f6e9e2017-01-10 17:14:56267
268 missing = sorted(missing)
wychene7a3d6482017-04-29 07:12:17269 nonexisting = sorted(nonexisting)
wychen037f6e9e2017-01-10 17:14:56270
wychen0735fd762017-06-03 07:53:26271 DumpJson(sorted(missing + nonexisting))
wychen037f6e9e2017-01-10 17:14:56272
wychene7a3d6482017-04-29 07:12:17273 if len(missing) == 0 and len(nonexisting) == 0:
wychen037f6e9e2017-01-10 17:14:56274 return 0
275
wychene7a3d6482017-04-29 07:12:17276 if len(missing) > 0:
Raul Tambre9e24293b2019-05-12 06:11:07277 print('\nThe following files should be included in gn files:')
wychene7a3d6482017-04-29 07:12:17278 for i in missing:
Raul Tambre9e24293b2019-05-12 06:11:07279 print(i)
wychene7a3d6482017-04-29 07:12:17280
281 if len(nonexisting) > 0:
Raul Tambre9e24293b2019-05-12 06:11:07282 print('\nThe following non-existing files should be removed from gn files:')
wychene7a3d6482017-04-29 07:12:17283 for i in nonexisting:
Raul Tambre9e24293b2019-05-12 06:11:07284 print(i)
wychene7a3d6482017-04-29 07:12:17285
wychen8cc31232017-06-13 10:21:23286 if args.verbose:
287 # Only get detailed obj dependency here since it is slower.
288 GetHeadersFromNinja(args.out_dir, False, d_q)
289 d, d_err = d_q.get()
Raul Tambre9e24293b2019-05-12 06:11:07290 print('\nDetailed dependency info:')
wychen8cc31232017-06-13 10:21:23291 for f in missing:
Raul Tambre9e24293b2019-05-12 06:11:07292 print(f)
wychen8cc31232017-06-13 10:21:23293 for cc in d[f]:
Raul Tambre9e24293b2019-05-12 06:11:07294 print(' ', cc)
wychen8cc31232017-06-13 10:21:23295
Raul Tambre9e24293b2019-05-12 06:11:07296 print('\nMissing headers sorted by number of affected object files:')
wychen8cc31232017-06-13 10:21:23297 count = {k: len(v) for (k, v) in d.iteritems()}
298 for f in sorted(count, key=count.get, reverse=True):
299 if f in missing:
Raul Tambre9e24293b2019-05-12 06:11:07300 print(count[f], f)
wychen8cc31232017-06-13 10:21:23301
Wei-Yin Chen (陳威尹)df00f5d2019-03-04 21:25:22302 if args.json:
303 # Assume running on the bots. Temporarily return 0 before
304 # https://crbug.com/937847 is fixed.
305 return 0
wychen037f6e9e2017-01-10 17:14:56306 return 1
307
308
309if __name__ == '__main__':
310 sys.exit(main())