blob: d6d6cc6b7faf529f70cc7c32d57b233149115827 [file] [log] [blame]
Adam Langley9e1a6602015-05-05 17:47:53 -07001# Copyright (c) 2015, Google Inc.
2#
3# Permission to use, copy, modify, and/or distribute this software for any
4# purpose with or without fee is hereby granted, provided that the above
5# copyright notice and this permission notice appear in all copies.
6#
7# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
Matt Braithwaite16695892016-06-09 09:34:11 -070015"""Enumerates source files for consumption by various build systems."""
Adam Langley9e1a6602015-05-05 17:47:53 -070016
Matt Braithwaite16695892016-06-09 09:34:11 -070017import optparse
Adam Langley9e1a6602015-05-05 17:47:53 -070018import os
19import subprocess
20import sys
Adam Langley9c164b22015-06-10 18:54:47 -070021import json
Adam Langley9e1a6602015-05-05 17:47:53 -070022
23
24# OS_ARCH_COMBOS maps from OS and platform to the OpenSSL assembly "style" for
25# that platform and the extension used by asm files.
26OS_ARCH_COMBOS = [
27 ('linux', 'arm', 'linux32', [], 'S'),
28 ('linux', 'aarch64', 'linux64', [], 'S'),
David Benjamin9f16ce12016-09-27 16:30:22 -040029 ('linux', 'ppc64le', 'ppc64le', [], 'S'),
Adam Langley9e1a6602015-05-05 17:47:53 -070030 ('linux', 'x86', 'elf', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
31 ('linux', 'x86_64', 'elf', [], 'S'),
32 ('mac', 'x86', 'macosx', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
33 ('mac', 'x86_64', 'macosx', [], 'S'),
34 ('win', 'x86', 'win32n', ['-DOPENSSL_IA32_SSE2'], 'asm'),
35 ('win', 'x86_64', 'nasm', [], 'asm'),
36]
37
38# NON_PERL_FILES enumerates assembly files that are not processed by the
39# perlasm system.
40NON_PERL_FILES = {
41 ('linux', 'arm'): [
Adam Langley7b8b9c12016-01-04 07:13:00 -080042 'src/crypto/curve25519/asm/x25519-asm-arm.S',
David Benjamin3c4a5cb2016-03-29 17:43:31 -040043 'src/crypto/poly1305/poly1305_arm_asm.S',
Adam Langley9e1a6602015-05-05 17:47:53 -070044 ],
Matt Braithwaitee021a242016-01-14 13:41:46 -080045 ('linux', 'x86_64'): [
46 'src/crypto/curve25519/asm/x25519-asm-x86_64.S',
47 ],
Piotr Sikora8ca0b412016-06-02 11:59:21 -070048 ('mac', 'x86_64'): [
49 'src/crypto/curve25519/asm/x25519-asm-x86_64.S',
50 ],
Adam Langley9e1a6602015-05-05 17:47:53 -070051}
52
Matt Braithwaite16695892016-06-09 09:34:11 -070053PREFIX = None
54
55
56def PathOf(x):
57 return x if not PREFIX else os.path.join(PREFIX, x)
58
Adam Langley9e1a6602015-05-05 17:47:53 -070059
Adam Langley9e1a6602015-05-05 17:47:53 -070060class Android(object):
61
62 def __init__(self):
63 self.header = \
64"""# Copyright (C) 2015 The Android Open Source Project
65#
66# Licensed under the Apache License, Version 2.0 (the "License");
67# you may not use this file except in compliance with the License.
68# You may obtain a copy of the License at
69#
70# http://www.apache.org/licenses/LICENSE-2.0
71#
72# Unless required by applicable law or agreed to in writing, software
73# distributed under the License is distributed on an "AS IS" BASIS,
74# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
75# See the License for the specific language governing permissions and
76# limitations under the License.
77
Dan Willemsenb57e4fc2016-07-21 11:08:44 -070078# This file is created by generate_build_files.py. Do not edit manually.
79
Adam Langley9e1a6602015-05-05 17:47:53 -070080"""
81
82 def PrintVariableSection(self, out, name, files):
83 out.write('%s := \\\n' % name)
84 for f in sorted(files):
85 out.write(' %s\\\n' % f)
86 out.write('\n')
87
88 def WriteFiles(self, files, asm_outputs):
Dan Willemsenb57e4fc2016-07-21 11:08:44 -070089 # New Android.bp format
90 with open('sources.bp', 'w+') as blueprint:
91 blueprint.write(self.header.replace('#', '//'))
92
93 blueprint.write('cc_defaults {\n')
94 blueprint.write(' name: "libcrypto_sources",\n')
95 blueprint.write(' srcs: [\n')
David Benjamin8c29e7d2016-09-30 21:34:31 -040096 for f in sorted(files['crypto']):
Dan Willemsenb57e4fc2016-07-21 11:08:44 -070097 blueprint.write(' "%s",\n' % f)
98 blueprint.write(' ],\n')
99 blueprint.write(' target: {\n')
100
101 for ((osname, arch), asm_files) in asm_outputs:
Steven Valdez93d242b2016-10-06 13:49:01 -0400102 if osname != 'linux' or arch == 'ppc64le':
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700103 continue
104 if arch == 'aarch64':
105 arch = 'arm64'
106
107 blueprint.write(' android_%s: {\n' % arch)
108 blueprint.write(' srcs: [\n')
109 for f in sorted(asm_files):
110 blueprint.write(' "%s",\n' % f)
111 blueprint.write(' ],\n')
112 blueprint.write(' },\n')
113
114 if arch == 'x86' or arch == 'x86_64':
115 blueprint.write(' linux_%s: {\n' % arch)
116 blueprint.write(' srcs: [\n')
117 for f in sorted(asm_files):
118 blueprint.write(' "%s",\n' % f)
119 blueprint.write(' ],\n')
120 blueprint.write(' },\n')
121
122 blueprint.write(' },\n')
123 blueprint.write('}\n\n')
124
125 blueprint.write('cc_defaults {\n')
126 blueprint.write(' name: "libssl_sources",\n')
127 blueprint.write(' srcs: [\n')
128 for f in sorted(files['ssl']):
129 blueprint.write(' "%s",\n' % f)
130 blueprint.write(' ],\n')
131 blueprint.write('}\n\n')
132
133 blueprint.write('cc_defaults {\n')
134 blueprint.write(' name: "bssl_sources",\n')
135 blueprint.write(' srcs: [\n')
136 for f in sorted(files['tool']):
137 blueprint.write(' "%s",\n' % f)
138 blueprint.write(' ],\n')
139 blueprint.write('}\n\n')
140
141 blueprint.write('cc_defaults {\n')
142 blueprint.write(' name: "boringssl_test_support_sources",\n')
143 blueprint.write(' srcs: [\n')
144 for f in sorted(files['test_support']):
145 blueprint.write(' "%s",\n' % f)
146 blueprint.write(' ],\n')
147 blueprint.write('}\n\n')
148
149 blueprint.write('cc_defaults {\n')
David Benjamin96628432017-01-19 19:05:47 -0500150 blueprint.write(' name: "boringssl_crypto_test_sources",\n')
151 blueprint.write(' srcs: [\n')
152 for f in sorted(files['crypto_test']):
153 blueprint.write(' "%s",\n' % f)
154 blueprint.write(' ],\n')
155 blueprint.write('}\n\n')
156
157 blueprint.write('cc_defaults {\n')
158 blueprint.write(' name: "boringssl_ssl_test_sources",\n')
159 blueprint.write(' srcs: [\n')
160 for f in sorted(files['ssl_test']):
161 blueprint.write(' "%s",\n' % f)
162 blueprint.write(' ],\n')
163 blueprint.write('}\n\n')
164
165 blueprint.write('cc_defaults {\n')
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700166 blueprint.write(' name: "boringssl_tests_sources",\n')
167 blueprint.write(' srcs: [\n')
168 for f in sorted(files['test']):
169 blueprint.write(' "%s",\n' % f)
170 blueprint.write(' ],\n')
171 blueprint.write('}\n')
172
173 # Legacy Android.mk format, only used by Trusty in new branches
Adam Langley9e1a6602015-05-05 17:47:53 -0700174 with open('sources.mk', 'w+') as makefile:
175 makefile.write(self.header)
176
David Benjamin8c29e7d2016-09-30 21:34:31 -0400177 self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
Adam Langley9e1a6602015-05-05 17:47:53 -0700178
179 for ((osname, arch), asm_files) in asm_outputs:
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700180 if osname != 'linux':
181 continue
Adam Langley9e1a6602015-05-05 17:47:53 -0700182 self.PrintVariableSection(
183 makefile, '%s_%s_sources' % (osname, arch), asm_files)
184
185
Adam Langley049ef412015-06-09 18:20:57 -0700186class Bazel(object):
187 """Bazel outputs files suitable for including in Bazel files."""
188
189 def __init__(self):
190 self.firstSection = True
191 self.header = \
192"""# This file is created by generate_build_files.py. Do not edit manually.
193
194"""
195
196 def PrintVariableSection(self, out, name, files):
197 if not self.firstSection:
198 out.write('\n')
199 self.firstSection = False
200
201 out.write('%s = [\n' % name)
202 for f in sorted(files):
Matt Braithwaite16695892016-06-09 09:34:11 -0700203 out.write(' "%s",\n' % PathOf(f))
Adam Langley049ef412015-06-09 18:20:57 -0700204 out.write(']\n')
205
206 def WriteFiles(self, files, asm_outputs):
Chuck Haysc608d6b2015-10-06 17:54:16 -0700207 with open('BUILD.generated.bzl', 'w+') as out:
Adam Langley049ef412015-06-09 18:20:57 -0700208 out.write(self.header)
209
210 self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
Adam Langleyfd499932017-04-04 14:21:43 -0700211 self.PrintVariableSection(out, 'fips_fragments', files['fips_fragments'])
Adam Langley049ef412015-06-09 18:20:57 -0700212 self.PrintVariableSection(
213 out, 'ssl_internal_headers', files['ssl_internal_headers'])
214 self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
Adam Langleyfeca9e52017-01-23 13:07:50 -0800215 self.PrintVariableSection(out, 'ssl_c_sources', files['ssl_c'])
216 self.PrintVariableSection(out, 'ssl_cc_sources', files['ssl_cc'])
Adam Langley049ef412015-06-09 18:20:57 -0700217 self.PrintVariableSection(out, 'crypto_headers', files['crypto_headers'])
218 self.PrintVariableSection(
219 out, 'crypto_internal_headers', files['crypto_internal_headers'])
220 self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
221 self.PrintVariableSection(out, 'tool_sources', files['tool'])
Adam Langleyf11f2332016-06-30 11:56:19 -0700222 self.PrintVariableSection(out, 'tool_headers', files['tool_headers'])
Adam Langley049ef412015-06-09 18:20:57 -0700223
224 for ((osname, arch), asm_files) in asm_outputs:
Adam Langley049ef412015-06-09 18:20:57 -0700225 self.PrintVariableSection(
Piotr Sikora3f5fe602015-10-28 12:24:35 -0700226 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
Adam Langley049ef412015-06-09 18:20:57 -0700227
Chuck Haysc608d6b2015-10-06 17:54:16 -0700228 with open('BUILD.generated_tests.bzl', 'w+') as out:
Adam Langley9c164b22015-06-10 18:54:47 -0700229 out.write(self.header)
230
231 out.write('test_support_sources = [\n')
David Benjaminc5aa8412016-07-29 17:41:58 -0400232 for filename in sorted(files['test_support'] +
233 files['test_support_headers'] +
234 files['crypto_internal_headers'] +
235 files['ssl_internal_headers']):
Adam Langley9c164b22015-06-10 18:54:47 -0700236 if os.path.basename(filename) == 'malloc.cc':
237 continue
Matt Braithwaite16695892016-06-09 09:34:11 -0700238 out.write(' "%s",\n' % PathOf(filename))
Adam Langley9c164b22015-06-10 18:54:47 -0700239
Chuck Haysc608d6b2015-10-06 17:54:16 -0700240 out.write(']\n\n')
241
David Benjamin96628432017-01-19 19:05:47 -0500242 self.PrintVariableSection(out, 'crypto_test_sources',
243 files['crypto_test'])
244 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
245
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700246 out.write('def create_tests(copts, crypto, ssl):\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700247 name_counts = {}
248 for test in files['tests']:
249 name = os.path.basename(test[0])
250 name_counts[name] = name_counts.get(name, 0) + 1
251
252 first = True
Matthew Braithwaitea0cb7252017-04-26 14:34:52 -0700253 test_names = set()
Adam Langley9c164b22015-06-10 18:54:47 -0700254 for test in files['tests']:
255 name = os.path.basename(test[0])
256 if name_counts[name] > 1:
Matthew Braithwaitea0cb7252017-04-26 14:34:52 -0700257 if '/' in test[-1]:
258 arg = test[-1].replace('crypto/cipher/test/','') # boooring
259 arg = arg.replace('/', '_')
260 arg = os.path.splitext(arg)[0] # remove .txt
261 arg = arg.replace('_tests', '')
262 name += '_' + arg
Adam Langley9c164b22015-06-10 18:54:47 -0700263 else:
Matthew Braithwaitea0cb7252017-04-26 14:34:52 -0700264 name += '_' + test[-1].replace('-', '_')
265
266 if name in test_names:
267 raise ValueError("test name %s is not unique" % name)
268 test_names.add(name)
Adam Langley9c164b22015-06-10 18:54:47 -0700269
270 if not first:
271 out.write('\n')
272 first = False
273
Adam Langley9c164b22015-06-10 18:54:47 -0700274 for src in files['test']:
Matthew Braithwaite97104af2017-04-18 16:13:52 -0700275 # For example, basename(src/crypto/fipsmodule/aes/aes_test.cc)
276 # startswith basename(crypto/fipsmodule/aes_test).
277 if os.path.basename(src).startswith(os.path.basename(test[0]) + '.'):
Adam Langley9c164b22015-06-10 18:54:47 -0700278 src = src
279 break
280 else:
281 raise ValueError("Can't find source for %s" % test[0])
282
Chuck Haysc608d6b2015-10-06 17:54:16 -0700283 out.write(' native.cc_test(\n')
284 out.write(' name = "%s",\n' % name)
285 out.write(' size = "small",\n')
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700286 out.write(' srcs = ["%s"] + test_support_sources,\n' %
Matt Braithwaite16695892016-06-09 09:34:11 -0700287 PathOf(src))
Adam Langley9c164b22015-06-10 18:54:47 -0700288
289 data_files = []
290 if len(test) > 1:
291
Chuck Haysc608d6b2015-10-06 17:54:16 -0700292 out.write(' args = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700293 for arg in test[1:]:
294 if '/' in arg:
Matt Braithwaite16695892016-06-09 09:34:11 -0700295 out.write(' "$(location %s)",\n' %
296 PathOf(os.path.join('src', arg)))
Adam Langley9c164b22015-06-10 18:54:47 -0700297 data_files.append('src/%s' % arg)
298 else:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700299 out.write(' "%s",\n' % arg)
300 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700301
Adam Langleyd7b90022016-11-17 09:02:01 -0800302 out.write(' copts = copts + ["-DBORINGSSL_SHARED_LIBRARY"],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700303
304 if len(data_files) > 0:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700305 out.write(' data = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700306 for filename in data_files:
Matt Braithwaite16695892016-06-09 09:34:11 -0700307 out.write(' "%s",\n' % PathOf(filename))
Chuck Haysc608d6b2015-10-06 17:54:16 -0700308 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700309
310 if 'ssl/' in test[0]:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700311 out.write(' deps = [\n')
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700312 out.write(' crypto,\n')
313 out.write(' ssl,\n')
Chuck Haysc608d6b2015-10-06 17:54:16 -0700314 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700315 else:
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700316 out.write(' deps = [crypto],\n')
Chuck Haysc608d6b2015-10-06 17:54:16 -0700317 out.write(' )\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700318
Adam Langley049ef412015-06-09 18:20:57 -0700319
David Benjamin38d01c62016-04-21 18:47:57 -0400320class GN(object):
321
322 def __init__(self):
323 self.firstSection = True
324 self.header = \
325"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
326# Use of this source code is governed by a BSD-style license that can be
327# found in the LICENSE file.
328
329# This file is created by generate_build_files.py. Do not edit manually.
330
331"""
332
333 def PrintVariableSection(self, out, name, files):
334 if not self.firstSection:
335 out.write('\n')
336 self.firstSection = False
337
338 out.write('%s = [\n' % name)
339 for f in sorted(files):
340 out.write(' "%s",\n' % f)
341 out.write(']\n')
342
343 def WriteFiles(self, files, asm_outputs):
344 with open('BUILD.generated.gni', 'w+') as out:
345 out.write(self.header)
346
David Benjaminc5aa8412016-07-29 17:41:58 -0400347 self.PrintVariableSection(out, 'crypto_sources',
348 files['crypto'] + files['crypto_headers'] +
349 files['crypto_internal_headers'])
350 self.PrintVariableSection(out, 'ssl_sources',
351 files['ssl'] + files['ssl_headers'] +
352 files['ssl_internal_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400353
354 for ((osname, arch), asm_files) in asm_outputs:
355 self.PrintVariableSection(
356 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
357
358 fuzzers = [os.path.splitext(os.path.basename(fuzzer))[0]
359 for fuzzer in files['fuzz']]
360 self.PrintVariableSection(out, 'fuzzers', fuzzers)
361
362 with open('BUILD.generated_tests.gni', 'w+') as out:
363 self.firstSection = True
364 out.write(self.header)
365
David Benjamin96628432017-01-19 19:05:47 -0500366 self.PrintVariableSection(out, 'test_support_sources',
David Benjaminc5aa8412016-07-29 17:41:58 -0400367 files['test_support'] +
368 files['test_support_headers'])
David Benjamin96628432017-01-19 19:05:47 -0500369 self.PrintVariableSection(out, 'crypto_test_sources',
370 files['crypto_test'])
371 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
David Benjamin38d01c62016-04-21 18:47:57 -0400372 out.write('\n')
373
374 out.write('template("create_tests") {\n')
375
376 all_tests = []
377 for test in sorted(files['test']):
378 test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
379 all_tests.append(test_name)
380
381 out.write(' executable("%s") {\n' % test_name)
382 out.write(' sources = [\n')
383 out.write(' "%s",\n' % test)
384 out.write(' ]\n')
David Benjamin96628432017-01-19 19:05:47 -0500385 out.write(' sources += test_support_sources\n')
David Benjaminb3be1cf2016-04-27 19:15:06 -0400386 out.write(' if (defined(invoker.configs_exclude)) {\n')
387 out.write(' configs -= invoker.configs_exclude\n')
388 out.write(' }\n')
David Benjamin38d01c62016-04-21 18:47:57 -0400389 out.write(' configs += invoker.configs\n')
Tom Anderson68f84f52017-05-24 20:20:11 -0700390 out.write(' deps = invoker.deps + ')
391 out.write('[ "//build/config:exe_and_shlib_deps" ]\n')
David Benjamin38d01c62016-04-21 18:47:57 -0400392 out.write(' }\n')
393 out.write('\n')
394
395 out.write(' group(target_name) {\n')
396 out.write(' deps = [\n')
397 for test_name in sorted(all_tests):
398 out.write(' ":%s",\n' % test_name)
399 out.write(' ]\n')
400 out.write(' }\n')
401 out.write('}\n')
402
403
404class GYP(object):
405
406 def __init__(self):
407 self.header = \
408"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
409# Use of this source code is governed by a BSD-style license that can be
410# found in the LICENSE file.
411
412# This file is created by generate_build_files.py. Do not edit manually.
413
414"""
415
416 def PrintVariableSection(self, out, name, files):
417 out.write(' \'%s\': [\n' % name)
418 for f in sorted(files):
419 out.write(' \'%s\',\n' % f)
420 out.write(' ],\n')
421
422 def WriteFiles(self, files, asm_outputs):
423 with open('boringssl.gypi', 'w+') as gypi:
424 gypi.write(self.header + '{\n \'variables\': {\n')
425
David Benjaminc5aa8412016-07-29 17:41:58 -0400426 self.PrintVariableSection(gypi, 'boringssl_ssl_sources',
427 files['ssl'] + files['ssl_headers'] +
428 files['ssl_internal_headers'])
429 self.PrintVariableSection(gypi, 'boringssl_crypto_sources',
430 files['crypto'] + files['crypto_headers'] +
431 files['crypto_internal_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400432
433 for ((osname, arch), asm_files) in asm_outputs:
434 self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
435 (osname, arch), asm_files)
436
437 gypi.write(' }\n}\n')
438
David Benjamin38d01c62016-04-21 18:47:57 -0400439
Adam Langley9e1a6602015-05-05 17:47:53 -0700440def FindCMakeFiles(directory):
441 """Returns list of all CMakeLists.txt files recursively in directory."""
442 cmakefiles = []
443
444 for (path, _, filenames) in os.walk(directory):
445 for filename in filenames:
446 if filename == 'CMakeLists.txt':
447 cmakefiles.append(os.path.join(path, filename))
448
449 return cmakefiles
450
Adam Langleyfd499932017-04-04 14:21:43 -0700451def OnlyFIPSFragments(path, dent, is_dir):
Matthew Braithwaite95511e92017-05-08 16:38:03 -0700452 return is_dir or (path.startswith(
453 os.path.join('src', 'crypto', 'fipsmodule', '')) and
454 NoTests(path, dent, is_dir))
Adam Langley9e1a6602015-05-05 17:47:53 -0700455
Adam Langleyfd499932017-04-04 14:21:43 -0700456def NoTestsNorFIPSFragments(path, dent, is_dir):
Adam Langley323f1eb2017-04-06 17:29:10 -0700457 return (NoTests(path, dent, is_dir) and
458 (is_dir or not OnlyFIPSFragments(path, dent, is_dir)))
Adam Langleyfd499932017-04-04 14:21:43 -0700459
460def NoTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700461 """Filter function that can be passed to FindCFiles in order to remove test
462 sources."""
463 if is_dir:
464 return dent != 'test'
465 return 'test.' not in dent and not dent.startswith('example_')
466
467
Adam Langleyfd499932017-04-04 14:21:43 -0700468def OnlyTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700469 """Filter function that can be passed to FindCFiles in order to remove
470 non-test sources."""
471 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400472 return dent != 'test'
Adam Langley9e1a6602015-05-05 17:47:53 -0700473 return '_test.' in dent or dent.startswith('example_')
474
475
Adam Langleyfd499932017-04-04 14:21:43 -0700476def AllFiles(path, dent, is_dir):
David Benjamin26073832015-05-11 20:52:48 -0400477 """Filter function that can be passed to FindCFiles in order to include all
478 sources."""
479 return True
480
481
Adam Langleyfd499932017-04-04 14:21:43 -0700482def NoTestRunnerFiles(path, dent, is_dir):
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700483 """Filter function that can be passed to FindCFiles or FindHeaderFiles in
484 order to exclude test runner files."""
485 # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
486 # are in their own subpackage, from being included in boringssl/BUILD files.
487 return not is_dir or dent != 'runner'
488
489
David Benjamin3ecd0a52017-05-19 15:26:18 -0400490def NotGTestSupport(path, dent, is_dir):
491 return 'gtest' not in dent
David Benjamin96628432017-01-19 19:05:47 -0500492
493
Adam Langleyfd499932017-04-04 14:21:43 -0700494def SSLHeaderFiles(path, dent, is_dir):
Adam Langley049ef412015-06-09 18:20:57 -0700495 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h']
496
497
Adam Langley9e1a6602015-05-05 17:47:53 -0700498def FindCFiles(directory, filter_func):
499 """Recurses through directory and returns a list of paths to all the C source
500 files that pass filter_func."""
501 cfiles = []
502
503 for (path, dirnames, filenames) in os.walk(directory):
504 for filename in filenames:
505 if not filename.endswith('.c') and not filename.endswith('.cc'):
506 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700507 if not filter_func(path, filename, False):
Adam Langley9e1a6602015-05-05 17:47:53 -0700508 continue
509 cfiles.append(os.path.join(path, filename))
510
511 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700512 if not filter_func(path, dirname, True):
Adam Langley9e1a6602015-05-05 17:47:53 -0700513 del dirnames[i]
514
515 return cfiles
516
517
Adam Langley049ef412015-06-09 18:20:57 -0700518def FindHeaderFiles(directory, filter_func):
519 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
520 hfiles = []
521
522 for (path, dirnames, filenames) in os.walk(directory):
523 for filename in filenames:
524 if not filename.endswith('.h'):
525 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700526 if not filter_func(path, filename, False):
Adam Langley049ef412015-06-09 18:20:57 -0700527 continue
528 hfiles.append(os.path.join(path, filename))
529
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700530 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700531 if not filter_func(path, dirname, True):
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700532 del dirnames[i]
533
Adam Langley049ef412015-06-09 18:20:57 -0700534 return hfiles
535
536
Adam Langley9e1a6602015-05-05 17:47:53 -0700537def ExtractPerlAsmFromCMakeFile(cmakefile):
538 """Parses the contents of the CMakeLists.txt file passed as an argument and
539 returns a list of all the perlasm() directives found in the file."""
540 perlasms = []
541 with open(cmakefile) as f:
542 for line in f:
543 line = line.strip()
544 if not line.startswith('perlasm('):
545 continue
546 if not line.endswith(')'):
547 raise ValueError('Bad perlasm line in %s' % cmakefile)
548 # Remove "perlasm(" from start and ")" from end
549 params = line[8:-1].split()
550 if len(params) < 2:
551 raise ValueError('Bad perlasm line in %s' % cmakefile)
552 perlasms.append({
553 'extra_args': params[2:],
554 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
555 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
556 })
557
558 return perlasms
559
560
561def ReadPerlAsmOperations():
562 """Returns a list of all perlasm() directives found in CMake config files in
563 src/."""
564 perlasms = []
565 cmakefiles = FindCMakeFiles('src')
566
567 for cmakefile in cmakefiles:
568 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
569
570 return perlasms
571
572
573def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
574 """Runs the a perlasm script and puts the output into output_filename."""
575 base_dir = os.path.dirname(output_filename)
576 if not os.path.isdir(base_dir):
577 os.makedirs(base_dir)
David Benjaminfdd8e9c2016-06-26 13:18:50 -0400578 subprocess.check_call(
579 ['perl', input_filename, perlasm_style] + extra_args + [output_filename])
Adam Langley9e1a6602015-05-05 17:47:53 -0700580
581
582def ArchForAsmFilename(filename):
583 """Returns the architectures that a given asm file should be compiled for
584 based on substrings in the filename."""
585
586 if 'x86_64' in filename or 'avx2' in filename:
587 return ['x86_64']
588 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
589 return ['x86']
590 elif 'armx' in filename:
591 return ['arm', 'aarch64']
592 elif 'armv8' in filename:
593 return ['aarch64']
594 elif 'arm' in filename:
595 return ['arm']
David Benjamin9f16ce12016-09-27 16:30:22 -0400596 elif 'ppc' in filename:
597 return ['ppc64le']
Adam Langley9e1a6602015-05-05 17:47:53 -0700598 else:
599 raise ValueError('Unknown arch for asm filename: ' + filename)
600
601
602def WriteAsmFiles(perlasms):
603 """Generates asm files from perlasm directives for each supported OS x
604 platform combination."""
605 asmfiles = {}
606
607 for osarch in OS_ARCH_COMBOS:
608 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
609 key = (osname, arch)
610 outDir = '%s-%s' % key
611
612 for perlasm in perlasms:
613 filename = os.path.basename(perlasm['input'])
614 output = perlasm['output']
615 if not output.startswith('src'):
616 raise ValueError('output missing src: %s' % output)
617 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200618 if output.endswith('-armx.${ASM_EXT}'):
619 output = output.replace('-armx',
620 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700621 output = output.replace('${ASM_EXT}', asm_ext)
622
623 if arch in ArchForAsmFilename(filename):
624 PerlAsm(output, perlasm['input'], perlasm_style,
625 perlasm['extra_args'] + extra_args)
626 asmfiles.setdefault(key, []).append(output)
627
628 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
629 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
630
631 return asmfiles
632
633
David Benjamin3ecd0a52017-05-19 15:26:18 -0400634def ExtractVariablesFromCMakeFile(cmakefile):
635 """Parses the contents of the CMakeLists.txt file passed as an argument and
636 returns a dictionary of exported source lists."""
637 variables = {}
638 in_set_command = False
639 set_command = []
640 with open(cmakefile) as f:
641 for line in f:
642 if '#' in line:
643 line = line[:line.index('#')]
644 line = line.strip()
645
646 if not in_set_command:
647 if line.startswith('set('):
648 in_set_command = True
649 set_command = []
650 elif line == ')':
651 in_set_command = False
652 if not set_command:
653 raise ValueError('Empty set command')
654 variables[set_command[0]] = set_command[1:]
655 else:
656 set_command.extend([c for c in line.split(' ') if c])
657
658 if in_set_command:
659 raise ValueError('Unfinished set command')
660 return variables
661
662
David Benjamin1d5a5702017-02-13 22:11:49 -0500663def IsGTest(path):
664 with open(path) as f:
665 return "#include <gtest/gtest.h>" in f.read()
666
667
Adam Langley049ef412015-06-09 18:20:57 -0700668def main(platforms):
David Benjamin3ecd0a52017-05-19 15:26:18 -0400669 cmake = ExtractVariablesFromCMakeFile(os.path.join('src', 'sources.cmake'))
Adam Langleyfd499932017-04-04 14:21:43 -0700670 crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTestsNorFIPSFragments)
671 fips_fragments = FindCFiles(os.path.join('src', 'crypto', 'fipsmodule'), OnlyFIPSFragments)
Adam Langleyfeca9e52017-01-23 13:07:50 -0800672 ssl_source_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
David Benjamin38d01c62016-04-21 18:47:57 -0400673 tool_c_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
Adam Langleyf11f2332016-06-30 11:56:19 -0700674 tool_h_files = FindHeaderFiles(os.path.join('src', 'tool'), AllFiles)
Adam Langley9e1a6602015-05-05 17:47:53 -0700675
676 # Generate err_data.c
677 with open('err_data.c', 'w+') as err_data:
678 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
679 cwd=os.path.join('src', 'crypto', 'err'),
680 stdout=err_data)
681 crypto_c_files.append('err_data.c')
682
David Benjamin38d01c62016-04-21 18:47:57 -0400683 test_support_c_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
David Benjamin3ecd0a52017-05-19 15:26:18 -0400684 NotGTestSupport)
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700685 test_support_h_files = (
686 FindHeaderFiles(os.path.join('src', 'crypto', 'test'), AllFiles) +
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700687 FindHeaderFiles(os.path.join('src', 'ssl', 'test'), NoTestRunnerFiles))
David Benjamin26073832015-05-11 20:52:48 -0400688
David Benjamin3ecd0a52017-05-19 15:26:18 -0400689 # Generate crypto_test_data.cc
690 with open('crypto_test_data.cc', 'w+') as out:
691 subprocess.check_call(
692 ['go', 'run', 'util/embed_test_data.go'] + cmake['CRYPTO_TEST_DATA'],
693 cwd='src',
694 stdout=out)
695
David Benjamin1d5a5702017-02-13 22:11:49 -0500696 test_c_files = []
David Benjamin3ecd0a52017-05-19 15:26:18 -0400697 crypto_test_files = [
698 'crypto_test_data.cc',
699 'src/crypto/test/file_test_gtest.cc',
700 'src/crypto/test/gtest_main.cc',
701 ]
David Benjamin1d5a5702017-02-13 22:11:49 -0500702 # TODO(davidben): Remove this loop once all tests are converted.
703 for path in FindCFiles(os.path.join('src', 'crypto'), OnlyTests):
704 if IsGTest(path):
705 crypto_test_files.append(path)
Adam Langley82bad052017-04-12 13:16:10 -0700706 else:
David Benjamin1d5a5702017-02-13 22:11:49 -0500707 test_c_files.append(path)
708
709 ssl_test_files = FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
710 ssl_test_files.append('src/crypto/test/gtest_main.cc')
Adam Langley9e1a6602015-05-05 17:47:53 -0700711
David Benjamin38d01c62016-04-21 18:47:57 -0400712 fuzz_c_files = FindCFiles(os.path.join('src', 'fuzz'), NoTests)
713
Adam Langley049ef412015-06-09 18:20:57 -0700714 ssl_h_files = (
715 FindHeaderFiles(
716 os.path.join('src', 'include', 'openssl'),
717 SSLHeaderFiles))
718
Adam Langleyfd499932017-04-04 14:21:43 -0700719 def NotSSLHeaderFiles(path, filename, is_dir):
720 return not SSLHeaderFiles(path, filename, is_dir)
Adam Langley049ef412015-06-09 18:20:57 -0700721 crypto_h_files = (
722 FindHeaderFiles(
723 os.path.join('src', 'include', 'openssl'),
724 NotSSLHeaderFiles))
725
726 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
727 crypto_internal_h_files = FindHeaderFiles(
728 os.path.join('src', 'crypto'), NoTests)
729
Adam Langley9c164b22015-06-10 18:54:47 -0700730 with open('src/util/all_tests.json', 'r') as f:
731 tests = json.load(f)
David Benjamin96628432017-01-19 19:05:47 -0500732 # For now, GTest-based tests are specified manually.
733 tests = [test for test in tests if test[0] not in ['crypto/crypto_test',
734 'decrepit/decrepit_test',
735 'ssl/ssl_test']]
Matthew Braithwaite97104af2017-04-18 16:13:52 -0700736 # The same test name can appear multiple times with different arguments. So,
737 # make a set to get a list of unique test binaries.
738 test_names = set([test[0] for test in tests])
739 test_binaries = set(map(os.path.basename, test_names))
740 # Make sure the test basenames are unique.
741 if len(test_binaries) != len(set(test_names)):
742 raise ValueError('non-unique test basename')
743 # Ensure a 1:1 correspondence between test sources and tests. This
744 # guarantees that the Bazel output includes everything in the JSON.
745 # Sometimes, a test's source isn't in the same directory as the test,
746 # which we handle by considering only the basename.
747 test_sources = set(map(os.path.basename, [
Adam Langley9c164b22015-06-10 18:54:47 -0700748 test.replace('.cc', '').replace('.c', '').replace(
749 'src/',
750 '')
Matthew Braithwaite97104af2017-04-18 16:13:52 -0700751 for test in test_c_files]))
Adam Langley9c164b22015-06-10 18:54:47 -0700752 if test_binaries != test_sources:
753 print 'Test sources and configured tests do not match'
754 a = test_binaries.difference(test_sources)
755 if len(a) > 0:
756 print 'These tests are configured without sources: ' + str(a)
757 b = test_sources.difference(test_binaries)
758 if len(b) > 0:
759 print 'These test sources are not configured: ' + str(b)
760
Adam Langley9e1a6602015-05-05 17:47:53 -0700761 files = {
762 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700763 'crypto_headers': crypto_h_files,
764 'crypto_internal_headers': crypto_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500765 'crypto_test': sorted(crypto_test_files),
Adam Langleyfd499932017-04-04 14:21:43 -0700766 'fips_fragments': fips_fragments,
David Benjamin38d01c62016-04-21 18:47:57 -0400767 'fuzz': fuzz_c_files,
Adam Langleyfeca9e52017-01-23 13:07:50 -0800768 'ssl': ssl_source_files,
769 'ssl_c': [s for s in ssl_source_files if s.endswith('.c')],
770 'ssl_cc': [s for s in ssl_source_files if s.endswith('.cc')],
Adam Langley049ef412015-06-09 18:20:57 -0700771 'ssl_headers': ssl_h_files,
772 'ssl_internal_headers': ssl_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500773 'ssl_test': sorted(ssl_test_files),
David Benjamin38d01c62016-04-21 18:47:57 -0400774 'tool': tool_c_files,
Adam Langleyf11f2332016-06-30 11:56:19 -0700775 'tool_headers': tool_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700776 'test': test_c_files,
David Benjaminc5aa8412016-07-29 17:41:58 -0400777 'test_support': test_support_c_files,
778 'test_support_headers': test_support_h_files,
Adam Langley9c164b22015-06-10 18:54:47 -0700779 'tests': tests,
Adam Langley9e1a6602015-05-05 17:47:53 -0700780 }
781
782 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
783
Adam Langley049ef412015-06-09 18:20:57 -0700784 for platform in platforms:
785 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700786
787 return 0
788
789
Adam Langley9e1a6602015-05-05 17:47:53 -0700790if __name__ == '__main__':
Matt Braithwaite16695892016-06-09 09:34:11 -0700791 parser = optparse.OptionParser(usage='Usage: %prog [--prefix=<path>]'
David Benjamin8c29e7d2016-09-30 21:34:31 -0400792 ' [android|bazel|gn|gyp]')
Matt Braithwaite16695892016-06-09 09:34:11 -0700793 parser.add_option('--prefix', dest='prefix',
794 help='For Bazel, prepend argument to all source files')
795 options, args = parser.parse_args(sys.argv[1:])
796 PREFIX = options.prefix
797
798 if not args:
799 parser.print_help()
800 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700801
Adam Langley049ef412015-06-09 18:20:57 -0700802 platforms = []
Matt Braithwaite16695892016-06-09 09:34:11 -0700803 for s in args:
David Benjamin38d01c62016-04-21 18:47:57 -0400804 if s == 'android':
Adam Langley049ef412015-06-09 18:20:57 -0700805 platforms.append(Android())
Adam Langley049ef412015-06-09 18:20:57 -0700806 elif s == 'bazel':
807 platforms.append(Bazel())
David Benjamin38d01c62016-04-21 18:47:57 -0400808 elif s == 'gn':
809 platforms.append(GN())
810 elif s == 'gyp':
811 platforms.append(GYP())
Adam Langley049ef412015-06-09 18:20:57 -0700812 else:
Matt Braithwaite16695892016-06-09 09:34:11 -0700813 parser.print_help()
814 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700815
Adam Langley049ef412015-06-09 18:20:57 -0700816 sys.exit(main(platforms))