blob: 6bd3abc645f6a9979aa06e5ee07625dcc06ba3f7 [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 = [
David Benjaminf6584e72017-06-08 16:27:16 -040027 ('ios', 'arm', 'ios32', [], 'S'),
28 ('ios', 'aarch64', 'ios64', [], 'S'),
Adam Langley9e1a6602015-05-05 17:47:53 -070029 ('linux', 'arm', 'linux32', [], 'S'),
30 ('linux', 'aarch64', 'linux64', [], 'S'),
Adam Langley7c075b92017-05-22 15:31:13 -070031 ('linux', 'ppc64le', 'linux64le', [], 'S'),
Adam Langley9e1a6602015-05-05 17:47:53 -070032 ('linux', 'x86', 'elf', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
33 ('linux', 'x86_64', 'elf', [], 'S'),
34 ('mac', 'x86', 'macosx', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
35 ('mac', 'x86_64', 'macosx', [], 'S'),
36 ('win', 'x86', 'win32n', ['-DOPENSSL_IA32_SSE2'], 'asm'),
37 ('win', 'x86_64', 'nasm', [], 'asm'),
38]
39
40# NON_PERL_FILES enumerates assembly files that are not processed by the
41# perlasm system.
42NON_PERL_FILES = {
43 ('linux', 'arm'): [
Adam Langley7b8b9c12016-01-04 07:13:00 -080044 'src/crypto/curve25519/asm/x25519-asm-arm.S',
David Benjamin3c4a5cb2016-03-29 17:43:31 -040045 'src/crypto/poly1305/poly1305_arm_asm.S',
Adam Langley7b935932018-11-12 13:53:42 -080046 ],
47 ('linux', 'x86_64'): [
48 'src/crypto/hrss/asm/poly_rq_mul.S',
Adam Langley9e1a6602015-05-05 17:47:53 -070049 ],
50}
51
Matt Braithwaite16695892016-06-09 09:34:11 -070052PREFIX = None
Adam Langley990a3232018-05-22 10:02:59 -070053EMBED_TEST_DATA = True
Matt Braithwaite16695892016-06-09 09:34:11 -070054
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.
Adam Langley9e1a6602015-05-05 17:47:53 -070079"""
80
81 def PrintVariableSection(self, out, name, files):
82 out.write('%s := \\\n' % name)
83 for f in sorted(files):
84 out.write(' %s\\\n' % f)
85 out.write('\n')
86
87 def WriteFiles(self, files, asm_outputs):
Dan Willemsenb57e4fc2016-07-21 11:08:44 -070088 # New Android.bp format
89 with open('sources.bp', 'w+') as blueprint:
90 blueprint.write(self.header.replace('#', '//'))
91
Pete Bentley44544d92019-08-15 15:01:26 +010092 # Separate out BCM files to allow different compilation rules (specific to Android FIPS)
93 bcm_c_files = files['bcm_crypto']
94 non_bcm_c_files = [file for file in files['crypto'] if file not in bcm_c_files]
95 non_bcm_asm = self.FilterBcmAsm(asm_outputs, False)
96 bcm_asm = self.FilterBcmAsm(asm_outputs, True)
Dan Willemsenb57e4fc2016-07-21 11:08:44 -070097
Pete Bentley44544d92019-08-15 15:01:26 +010098 self.PrintDefaults(blueprint, 'libcrypto_sources', non_bcm_c_files, non_bcm_asm)
99 self.PrintDefaults(blueprint, 'libcrypto_bcm_sources', bcm_c_files, bcm_asm)
100 self.PrintDefaults(blueprint, 'libssl_sources', files['ssl'])
101 self.PrintDefaults(blueprint, 'bssl_sources', files['tool'])
102 self.PrintDefaults(blueprint, 'boringssl_test_support_sources', files['test_support'])
103 self.PrintDefaults(blueprint, 'boringssl_crypto_test_sources', files['crypto_test'])
104 self.PrintDefaults(blueprint, 'boringssl_ssl_test_sources', files['ssl_test'])
105
106 # Legacy Android.mk format, only used by Trusty in new branches
107 with open('sources.mk', 'w+') as makefile:
108 makefile.write(self.header)
109 makefile.write('\n')
110 self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
111
112 for ((osname, arch), asm_files) in asm_outputs:
113 if osname != 'linux':
114 continue
115 self.PrintVariableSection(
116 makefile, '%s_%s_sources' % (osname, arch), asm_files)
117
118 def PrintDefaults(self, blueprint, name, files, asm_outputs={}):
119 """Print a cc_defaults section from a list of C files and optionally assembly outputs"""
120 blueprint.write('\n')
121 blueprint.write('cc_defaults {\n')
122 blueprint.write(' name: "%s",\n' % name)
123 blueprint.write(' srcs: [\n')
124 for f in sorted(files):
125 blueprint.write(' "%s",\n' % f)
126 blueprint.write(' ],\n')
127
128 if asm_outputs:
129 blueprint.write(' target: {\n')
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700130 for ((osname, arch), asm_files) in asm_outputs:
Steven Valdez93d242b2016-10-06 13:49:01 -0400131 if osname != 'linux' or arch == 'ppc64le':
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700132 continue
133 if arch == 'aarch64':
134 arch = 'arm64'
135
Dan Willemsen2eb4bc52017-10-16 14:37:00 -0700136 blueprint.write(' linux_%s: {\n' % arch)
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700137 blueprint.write(' srcs: [\n')
138 for f in sorted(asm_files):
139 blueprint.write(' "%s",\n' % f)
140 blueprint.write(' ],\n')
141 blueprint.write(' },\n')
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700142 blueprint.write(' },\n')
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700143
Pete Bentley44544d92019-08-15 15:01:26 +0100144 blueprint.write('}\n')
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700145
Pete Bentley44544d92019-08-15 15:01:26 +0100146 def FilterBcmAsm(self, asm, want_bcm):
147 """Filter a list of assembly outputs based on whether they belong in BCM
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700148
Pete Bentley44544d92019-08-15 15:01:26 +0100149 Args:
150 asm: Assembly file lists to filter
151 want_bcm: If true then include BCM files, otherwise do not
Dan Willemsenb57e4fc2016-07-21 11:08:44 -0700152
Pete Bentley44544d92019-08-15 15:01:26 +0100153 Returns:
154 A copy of |asm| with files filtered according to |want_bcm|
155 """
156 return [(archinfo, filter(lambda p: ("/crypto/fipsmodule/" in p) == want_bcm, files))
157 for (archinfo, files) in asm]
Adam Langley9e1a6602015-05-05 17:47:53 -0700158
159
David Benjamineca48e52019-08-13 11:51:53 -0400160class AndroidCMake(object):
161
162 def __init__(self):
163 self.header = \
164"""# Copyright (C) 2019 The Android Open Source Project
165#
166# Licensed under the Apache License, Version 2.0 (the "License");
167# you may not use this file except in compliance with the License.
168# You may obtain a copy of the License at
169#
170# http://www.apache.org/licenses/LICENSE-2.0
171#
172# Unless required by applicable law or agreed to in writing, software
173# distributed under the License is distributed on an "AS IS" BASIS,
174# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
175# See the License for the specific language governing permissions and
176# limitations under the License.
177
178# This file is created by generate_build_files.py. Do not edit manually.
179# To specify a custom path prefix, set BORINGSSL_ROOT before including this
180# file, or use list(TRANSFORM ... PREPEND) from CMake 3.12.
181
182"""
183
184 def PrintVariableSection(self, out, name, files):
185 out.write('set(%s\n' % name)
186 for f in sorted(files):
187 # Ideally adding the prefix would be the caller's job, but
188 # list(TRANSFORM ... PREPEND) is only available starting CMake 3.12. When
189 # sources.cmake is the source of truth, we can ask Android to either write
190 # a CMake function or update to 3.12.
191 out.write(' ${BORINGSSL_ROOT}%s\n' % f)
192 out.write(')\n')
193
194 def WriteFiles(self, files, asm_outputs):
195 # The Android emulator uses a custom CMake buildsystem.
196 #
197 # TODO(davidben): Move our various source lists into sources.cmake and have
198 # Android consume that directly.
199 with open('android-sources.cmake', 'w+') as out:
200 out.write(self.header)
201
202 self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
203 self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
204 self.PrintVariableSection(out, 'tool_sources', files['tool'])
205 self.PrintVariableSection(out, 'test_support_sources',
206 files['test_support'])
207 self.PrintVariableSection(out, 'crypto_test_sources',
208 files['crypto_test'])
209 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
210
211 for ((osname, arch), asm_files) in asm_outputs:
212 self.PrintVariableSection(
213 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
214
215
Adam Langley049ef412015-06-09 18:20:57 -0700216class Bazel(object):
217 """Bazel outputs files suitable for including in Bazel files."""
218
219 def __init__(self):
220 self.firstSection = True
221 self.header = \
222"""# This file is created by generate_build_files.py. Do not edit manually.
223
224"""
225
226 def PrintVariableSection(self, out, name, files):
227 if not self.firstSection:
228 out.write('\n')
229 self.firstSection = False
230
231 out.write('%s = [\n' % name)
232 for f in sorted(files):
Matt Braithwaite16695892016-06-09 09:34:11 -0700233 out.write(' "%s",\n' % PathOf(f))
Adam Langley049ef412015-06-09 18:20:57 -0700234 out.write(']\n')
235
236 def WriteFiles(self, files, asm_outputs):
Chuck Haysc608d6b2015-10-06 17:54:16 -0700237 with open('BUILD.generated.bzl', 'w+') as out:
Adam Langley049ef412015-06-09 18:20:57 -0700238 out.write(self.header)
239
240 self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
Adam Langleyfd499932017-04-04 14:21:43 -0700241 self.PrintVariableSection(out, 'fips_fragments', files['fips_fragments'])
Adam Langley049ef412015-06-09 18:20:57 -0700242 self.PrintVariableSection(
243 out, 'ssl_internal_headers', files['ssl_internal_headers'])
244 self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
245 self.PrintVariableSection(out, 'crypto_headers', files['crypto_headers'])
246 self.PrintVariableSection(
247 out, 'crypto_internal_headers', files['crypto_internal_headers'])
248 self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
249 self.PrintVariableSection(out, 'tool_sources', files['tool'])
Adam Langleyf11f2332016-06-30 11:56:19 -0700250 self.PrintVariableSection(out, 'tool_headers', files['tool_headers'])
Adam Langley049ef412015-06-09 18:20:57 -0700251
252 for ((osname, arch), asm_files) in asm_outputs:
Adam Langley049ef412015-06-09 18:20:57 -0700253 self.PrintVariableSection(
Piotr Sikora3f5fe602015-10-28 12:24:35 -0700254 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
Adam Langley049ef412015-06-09 18:20:57 -0700255
Chuck Haysc608d6b2015-10-06 17:54:16 -0700256 with open('BUILD.generated_tests.bzl', 'w+') as out:
Adam Langley9c164b22015-06-10 18:54:47 -0700257 out.write(self.header)
258
259 out.write('test_support_sources = [\n')
David Benjaminc5aa8412016-07-29 17:41:58 -0400260 for filename in sorted(files['test_support'] +
261 files['test_support_headers'] +
262 files['crypto_internal_headers'] +
263 files['ssl_internal_headers']):
Adam Langley9c164b22015-06-10 18:54:47 -0700264 if os.path.basename(filename) == 'malloc.cc':
265 continue
Matt Braithwaite16695892016-06-09 09:34:11 -0700266 out.write(' "%s",\n' % PathOf(filename))
Adam Langley9c164b22015-06-10 18:54:47 -0700267
Adam Langley7b6acc52017-07-27 16:33:27 -0700268 out.write(']\n')
Chuck Haysc608d6b2015-10-06 17:54:16 -0700269
David Benjamin96628432017-01-19 19:05:47 -0500270 self.PrintVariableSection(out, 'crypto_test_sources',
271 files['crypto_test'])
272 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
Adam Langley990a3232018-05-22 10:02:59 -0700273 self.PrintVariableSection(out, 'crypto_test_data',
274 files['crypto_test_data'])
Adam Langley3e502c82019-10-16 09:56:38 -0700275 self.PrintVariableSection(out, 'urandom_test_sources',
276 files['urandom_test'])
David Benjamin96628432017-01-19 19:05:47 -0500277
Adam Langley049ef412015-06-09 18:20:57 -0700278
Robert Sloane091af42017-10-09 12:47:17 -0700279class Eureka(object):
280
281 def __init__(self):
282 self.header = \
283"""# Copyright (C) 2017 The Android Open Source Project
284#
285# Licensed under the Apache License, Version 2.0 (the "License");
286# you may not use this file except in compliance with the License.
287# You may obtain a copy of the License at
288#
289# http://www.apache.org/licenses/LICENSE-2.0
290#
291# Unless required by applicable law or agreed to in writing, software
292# distributed under the License is distributed on an "AS IS" BASIS,
293# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
294# See the License for the specific language governing permissions and
295# limitations under the License.
296
297# This file is created by generate_build_files.py. Do not edit manually.
298
299"""
300
301 def PrintVariableSection(self, out, name, files):
302 out.write('%s := \\\n' % name)
303 for f in sorted(files):
304 out.write(' %s\\\n' % f)
305 out.write('\n')
306
307 def WriteFiles(self, files, asm_outputs):
308 # Legacy Android.mk format
309 with open('eureka.mk', 'w+') as makefile:
310 makefile.write(self.header)
311
312 self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
313 self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
314 self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
315
316 for ((osname, arch), asm_files) in asm_outputs:
317 if osname != 'linux':
318 continue
319 self.PrintVariableSection(
320 makefile, '%s_%s_sources' % (osname, arch), asm_files)
321
322
David Benjamin38d01c62016-04-21 18:47:57 -0400323class GN(object):
324
325 def __init__(self):
326 self.firstSection = True
327 self.header = \
328"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
329# Use of this source code is governed by a BSD-style license that can be
330# found in the LICENSE file.
331
332# This file is created by generate_build_files.py. Do not edit manually.
333
334"""
335
336 def PrintVariableSection(self, out, name, files):
337 if not self.firstSection:
338 out.write('\n')
339 self.firstSection = False
340
341 out.write('%s = [\n' % name)
342 for f in sorted(files):
343 out.write(' "%s",\n' % f)
344 out.write(']\n')
345
346 def WriteFiles(self, files, asm_outputs):
347 with open('BUILD.generated.gni', 'w+') as out:
348 out.write(self.header)
349
David Benjaminc5aa8412016-07-29 17:41:58 -0400350 self.PrintVariableSection(out, 'crypto_sources',
James Robinson98dd68f2018-04-11 14:47:34 -0700351 files['crypto'] +
David Benjaminc5aa8412016-07-29 17:41:58 -0400352 files['crypto_internal_headers'])
James Robinson98dd68f2018-04-11 14:47:34 -0700353 self.PrintVariableSection(out, 'crypto_headers',
354 files['crypto_headers'])
David Benjaminc5aa8412016-07-29 17:41:58 -0400355 self.PrintVariableSection(out, 'ssl_sources',
James Robinson98dd68f2018-04-11 14:47:34 -0700356 files['ssl'] + files['ssl_internal_headers'])
357 self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400358
359 for ((osname, arch), asm_files) in asm_outputs:
360 self.PrintVariableSection(
361 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
362
363 fuzzers = [os.path.splitext(os.path.basename(fuzzer))[0]
364 for fuzzer in files['fuzz']]
365 self.PrintVariableSection(out, 'fuzzers', fuzzers)
366
367 with open('BUILD.generated_tests.gni', 'w+') as out:
368 self.firstSection = True
369 out.write(self.header)
370
David Benjamin96628432017-01-19 19:05:47 -0500371 self.PrintVariableSection(out, 'test_support_sources',
David Benjaminc5aa8412016-07-29 17:41:58 -0400372 files['test_support'] +
373 files['test_support_headers'])
David Benjamin96628432017-01-19 19:05:47 -0500374 self.PrintVariableSection(out, 'crypto_test_sources',
375 files['crypto_test'])
David Benjaminf014d602019-05-07 18:58:06 -0500376 self.PrintVariableSection(out, 'crypto_test_data',
377 files['crypto_test_data'])
David Benjamin96628432017-01-19 19:05:47 -0500378 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
David Benjamin38d01c62016-04-21 18:47:57 -0400379
380
381class GYP(object):
382
383 def __init__(self):
384 self.header = \
385"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
386# Use of this source code is governed by a BSD-style license that can be
387# found in the LICENSE file.
388
389# This file is created by generate_build_files.py. Do not edit manually.
390
391"""
392
393 def PrintVariableSection(self, out, name, files):
394 out.write(' \'%s\': [\n' % name)
395 for f in sorted(files):
396 out.write(' \'%s\',\n' % f)
397 out.write(' ],\n')
398
399 def WriteFiles(self, files, asm_outputs):
400 with open('boringssl.gypi', 'w+') as gypi:
401 gypi.write(self.header + '{\n \'variables\': {\n')
402
David Benjaminc5aa8412016-07-29 17:41:58 -0400403 self.PrintVariableSection(gypi, 'boringssl_ssl_sources',
404 files['ssl'] + files['ssl_headers'] +
405 files['ssl_internal_headers'])
406 self.PrintVariableSection(gypi, 'boringssl_crypto_sources',
407 files['crypto'] + files['crypto_headers'] +
408 files['crypto_internal_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400409
410 for ((osname, arch), asm_files) in asm_outputs:
411 self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
412 (osname, arch), asm_files)
413
414 gypi.write(' }\n}\n')
415
David Benjamin38d01c62016-04-21 18:47:57 -0400416
Adam Langley9e1a6602015-05-05 17:47:53 -0700417def FindCMakeFiles(directory):
418 """Returns list of all CMakeLists.txt files recursively in directory."""
419 cmakefiles = []
420
421 for (path, _, filenames) in os.walk(directory):
422 for filename in filenames:
423 if filename == 'CMakeLists.txt':
424 cmakefiles.append(os.path.join(path, filename))
425
426 return cmakefiles
427
Adam Langleyfd499932017-04-04 14:21:43 -0700428def OnlyFIPSFragments(path, dent, is_dir):
Matthew Braithwaite95511e92017-05-08 16:38:03 -0700429 return is_dir or (path.startswith(
430 os.path.join('src', 'crypto', 'fipsmodule', '')) and
431 NoTests(path, dent, is_dir))
Adam Langley9e1a6602015-05-05 17:47:53 -0700432
Adam Langleyfd499932017-04-04 14:21:43 -0700433def NoTestsNorFIPSFragments(path, dent, is_dir):
Adam Langley323f1eb2017-04-06 17:29:10 -0700434 return (NoTests(path, dent, is_dir) and
435 (is_dir or not OnlyFIPSFragments(path, dent, is_dir)))
Adam Langleyfd499932017-04-04 14:21:43 -0700436
437def NoTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700438 """Filter function that can be passed to FindCFiles in order to remove test
439 sources."""
440 if is_dir:
441 return dent != 'test'
David Benjamin96ee4a82017-07-09 23:46:47 -0400442 return 'test.' not in dent
Adam Langley9e1a6602015-05-05 17:47:53 -0700443
444
Adam Langleyfd499932017-04-04 14:21:43 -0700445def OnlyTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700446 """Filter function that can be passed to FindCFiles in order to remove
447 non-test sources."""
448 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400449 return dent != 'test'
David Benjamin96ee4a82017-07-09 23:46:47 -0400450 return '_test.' in dent
Adam Langley9e1a6602015-05-05 17:47:53 -0700451
452
Adam Langleyfd499932017-04-04 14:21:43 -0700453def AllFiles(path, dent, is_dir):
David Benjamin26073832015-05-11 20:52:48 -0400454 """Filter function that can be passed to FindCFiles in order to include all
455 sources."""
456 return True
457
458
Adam Langleyfd499932017-04-04 14:21:43 -0700459def NoTestRunnerFiles(path, dent, is_dir):
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700460 """Filter function that can be passed to FindCFiles or FindHeaderFiles in
461 order to exclude test runner files."""
462 # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
463 # are in their own subpackage, from being included in boringssl/BUILD files.
464 return not is_dir or dent != 'runner'
465
466
David Benjamin3ecd0a52017-05-19 15:26:18 -0400467def NotGTestSupport(path, dent, is_dir):
David Benjaminc3889632019-03-01 15:03:05 -0500468 return 'gtest' not in dent and 'abi_test' not in dent
David Benjamin96628432017-01-19 19:05:47 -0500469
470
Adam Langleyfd499932017-04-04 14:21:43 -0700471def SSLHeaderFiles(path, dent, is_dir):
Aaron Green0e150022018-10-16 12:05:29 -0700472 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h', 'srtp.h']
Adam Langley049ef412015-06-09 18:20:57 -0700473
474
Adam Langley9e1a6602015-05-05 17:47:53 -0700475def FindCFiles(directory, filter_func):
476 """Recurses through directory and returns a list of paths to all the C source
477 files that pass filter_func."""
478 cfiles = []
479
480 for (path, dirnames, filenames) in os.walk(directory):
481 for filename in filenames:
482 if not filename.endswith('.c') and not filename.endswith('.cc'):
483 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700484 if not filter_func(path, filename, False):
Adam Langley9e1a6602015-05-05 17:47:53 -0700485 continue
486 cfiles.append(os.path.join(path, filename))
487
488 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700489 if not filter_func(path, dirname, True):
Adam Langley9e1a6602015-05-05 17:47:53 -0700490 del dirnames[i]
491
492 return cfiles
493
494
Adam Langley049ef412015-06-09 18:20:57 -0700495def FindHeaderFiles(directory, filter_func):
496 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
497 hfiles = []
498
499 for (path, dirnames, filenames) in os.walk(directory):
500 for filename in filenames:
501 if not filename.endswith('.h'):
502 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700503 if not filter_func(path, filename, False):
Adam Langley049ef412015-06-09 18:20:57 -0700504 continue
505 hfiles.append(os.path.join(path, filename))
506
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700507 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700508 if not filter_func(path, dirname, True):
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700509 del dirnames[i]
510
Adam Langley049ef412015-06-09 18:20:57 -0700511 return hfiles
512
513
Adam Langley9e1a6602015-05-05 17:47:53 -0700514def ExtractPerlAsmFromCMakeFile(cmakefile):
515 """Parses the contents of the CMakeLists.txt file passed as an argument and
516 returns a list of all the perlasm() directives found in the file."""
517 perlasms = []
518 with open(cmakefile) as f:
519 for line in f:
520 line = line.strip()
521 if not line.startswith('perlasm('):
522 continue
523 if not line.endswith(')'):
524 raise ValueError('Bad perlasm line in %s' % cmakefile)
525 # Remove "perlasm(" from start and ")" from end
526 params = line[8:-1].split()
527 if len(params) < 2:
528 raise ValueError('Bad perlasm line in %s' % cmakefile)
529 perlasms.append({
530 'extra_args': params[2:],
531 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
532 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
533 })
534
535 return perlasms
536
537
538def ReadPerlAsmOperations():
539 """Returns a list of all perlasm() directives found in CMake config files in
540 src/."""
541 perlasms = []
542 cmakefiles = FindCMakeFiles('src')
543
544 for cmakefile in cmakefiles:
545 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
546
547 return perlasms
548
549
550def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
551 """Runs the a perlasm script and puts the output into output_filename."""
552 base_dir = os.path.dirname(output_filename)
553 if not os.path.isdir(base_dir):
554 os.makedirs(base_dir)
David Benjaminfdd8e9c2016-06-26 13:18:50 -0400555 subprocess.check_call(
556 ['perl', input_filename, perlasm_style] + extra_args + [output_filename])
Adam Langley9e1a6602015-05-05 17:47:53 -0700557
558
559def ArchForAsmFilename(filename):
560 """Returns the architectures that a given asm file should be compiled for
561 based on substrings in the filename."""
562
563 if 'x86_64' in filename or 'avx2' in filename:
564 return ['x86_64']
565 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
566 return ['x86']
567 elif 'armx' in filename:
568 return ['arm', 'aarch64']
569 elif 'armv8' in filename:
570 return ['aarch64']
571 elif 'arm' in filename:
572 return ['arm']
David Benjamin9f16ce12016-09-27 16:30:22 -0400573 elif 'ppc' in filename:
574 return ['ppc64le']
Adam Langley9e1a6602015-05-05 17:47:53 -0700575 else:
576 raise ValueError('Unknown arch for asm filename: ' + filename)
577
578
579def WriteAsmFiles(perlasms):
580 """Generates asm files from perlasm directives for each supported OS x
581 platform combination."""
582 asmfiles = {}
583
584 for osarch in OS_ARCH_COMBOS:
585 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
586 key = (osname, arch)
587 outDir = '%s-%s' % key
588
589 for perlasm in perlasms:
590 filename = os.path.basename(perlasm['input'])
591 output = perlasm['output']
592 if not output.startswith('src'):
593 raise ValueError('output missing src: %s' % output)
594 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200595 if output.endswith('-armx.${ASM_EXT}'):
596 output = output.replace('-armx',
597 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700598 output = output.replace('${ASM_EXT}', asm_ext)
599
600 if arch in ArchForAsmFilename(filename):
601 PerlAsm(output, perlasm['input'], perlasm_style,
602 perlasm['extra_args'] + extra_args)
603 asmfiles.setdefault(key, []).append(output)
604
605 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
606 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
607
608 return asmfiles
609
610
David Benjamin3ecd0a52017-05-19 15:26:18 -0400611def ExtractVariablesFromCMakeFile(cmakefile):
612 """Parses the contents of the CMakeLists.txt file passed as an argument and
613 returns a dictionary of exported source lists."""
614 variables = {}
615 in_set_command = False
616 set_command = []
617 with open(cmakefile) as f:
618 for line in f:
619 if '#' in line:
620 line = line[:line.index('#')]
621 line = line.strip()
622
623 if not in_set_command:
624 if line.startswith('set('):
625 in_set_command = True
626 set_command = []
627 elif line == ')':
628 in_set_command = False
629 if not set_command:
630 raise ValueError('Empty set command')
631 variables[set_command[0]] = set_command[1:]
632 else:
633 set_command.extend([c for c in line.split(' ') if c])
634
635 if in_set_command:
636 raise ValueError('Unfinished set command')
637 return variables
638
639
Adam Langley049ef412015-06-09 18:20:57 -0700640def main(platforms):
David Benjamin3ecd0a52017-05-19 15:26:18 -0400641 cmake = ExtractVariablesFromCMakeFile(os.path.join('src', 'sources.cmake'))
Andres Erbsen5b280a82017-10-30 15:58:33 +0000642 crypto_c_files = (FindCFiles(os.path.join('src', 'crypto'), NoTestsNorFIPSFragments) +
Adam Langley7f028812019-10-18 14:48:11 -0700643 FindCFiles(os.path.join('src', 'third_party', 'fiat'), NoTestsNorFIPSFragments))
Adam Langleyfd499932017-04-04 14:21:43 -0700644 fips_fragments = FindCFiles(os.path.join('src', 'crypto', 'fipsmodule'), OnlyFIPSFragments)
Adam Langleyfeca9e52017-01-23 13:07:50 -0800645 ssl_source_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
David Benjamin38d01c62016-04-21 18:47:57 -0400646 tool_c_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
Adam Langleyf11f2332016-06-30 11:56:19 -0700647 tool_h_files = FindHeaderFiles(os.path.join('src', 'tool'), AllFiles)
Adam Langley9e1a6602015-05-05 17:47:53 -0700648
David Benjamin0c9c1aa2017-12-12 15:19:20 -0500649 # third_party/fiat/p256.c lives in third_party/fiat, but it is a FIPS
650 # fragment, not a normal source file.
651 p256 = os.path.join('src', 'third_party', 'fiat', 'p256.c')
652 fips_fragments.append(p256)
653 crypto_c_files.remove(p256)
654
Pete Bentley44544d92019-08-15 15:01:26 +0100655 # BCM shared library C files
656 bcm_crypto_c_files = [
657 os.path.join('src', 'crypto', 'fipsmodule', 'bcm.c')
658 ]
659
Adam Langley9e1a6602015-05-05 17:47:53 -0700660 # Generate err_data.c
661 with open('err_data.c', 'w+') as err_data:
662 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
663 cwd=os.path.join('src', 'crypto', 'err'),
664 stdout=err_data)
665 crypto_c_files.append('err_data.c')
666
David Benjamin38d01c62016-04-21 18:47:57 -0400667 test_support_c_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
David Benjamin3ecd0a52017-05-19 15:26:18 -0400668 NotGTestSupport)
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700669 test_support_h_files = (
670 FindHeaderFiles(os.path.join('src', 'crypto', 'test'), AllFiles) +
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700671 FindHeaderFiles(os.path.join('src', 'ssl', 'test'), NoTestRunnerFiles))
David Benjamin26073832015-05-11 20:52:48 -0400672
Adam Langley990a3232018-05-22 10:02:59 -0700673 crypto_test_files = []
674 if EMBED_TEST_DATA:
675 # Generate crypto_test_data.cc
676 with open('crypto_test_data.cc', 'w+') as out:
677 subprocess.check_call(
678 ['go', 'run', 'util/embed_test_data.go'] + cmake['CRYPTO_TEST_DATA'],
679 cwd='src',
680 stdout=out)
681 crypto_test_files += ['crypto_test_data.cc']
David Benjamin3ecd0a52017-05-19 15:26:18 -0400682
Adam Langley990a3232018-05-22 10:02:59 -0700683 crypto_test_files += FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
David Benjamin96ee4a82017-07-09 23:46:47 -0400684 crypto_test_files += [
David Benjaminc3889632019-03-01 15:03:05 -0500685 'src/crypto/test/abi_test.cc',
David Benjamin3ecd0a52017-05-19 15:26:18 -0400686 'src/crypto/test/file_test_gtest.cc',
687 'src/crypto/test/gtest_main.cc',
688 ]
Adam Langley3e502c82019-10-16 09:56:38 -0700689 # urandom_test.cc is in a separate binary so that it can be test PRNG
690 # initialisation.
691 crypto_test_files = [
692 file for file in crypto_test_files
693 if not file.endswith('/urandom_test.cc')
694 ]
David Benjamin1d5a5702017-02-13 22:11:49 -0500695
696 ssl_test_files = FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
Robert Sloanae1e0872019-03-01 16:01:30 -0800697 ssl_test_files += [
698 'src/crypto/test/abi_test.cc',
699 'src/crypto/test/gtest_main.cc',
700 ]
Adam Langley9e1a6602015-05-05 17:47:53 -0700701
Adam Langley3e502c82019-10-16 09:56:38 -0700702 urandom_test_files = [
703 'src/crypto/fipsmodule/rand/urandom_test.cc',
704 ]
705
David Benjamin38d01c62016-04-21 18:47:57 -0400706 fuzz_c_files = FindCFiles(os.path.join('src', 'fuzz'), NoTests)
707
Adam Langley049ef412015-06-09 18:20:57 -0700708 ssl_h_files = (
709 FindHeaderFiles(
710 os.path.join('src', 'include', 'openssl'),
711 SSLHeaderFiles))
712
Adam Langleyfd499932017-04-04 14:21:43 -0700713 def NotSSLHeaderFiles(path, filename, is_dir):
714 return not SSLHeaderFiles(path, filename, is_dir)
Adam Langley049ef412015-06-09 18:20:57 -0700715 crypto_h_files = (
716 FindHeaderFiles(
717 os.path.join('src', 'include', 'openssl'),
718 NotSSLHeaderFiles))
719
720 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
Andres Erbsen5b280a82017-10-30 15:58:33 +0000721 crypto_internal_h_files = (
722 FindHeaderFiles(os.path.join('src', 'crypto'), NoTests) +
Adam Langley7f028812019-10-18 14:48:11 -0700723 FindHeaderFiles(os.path.join('src', 'third_party', 'fiat'), NoTests))
Adam Langley049ef412015-06-09 18:20:57 -0700724
Adam Langley9e1a6602015-05-05 17:47:53 -0700725 files = {
Pete Bentley44544d92019-08-15 15:01:26 +0100726 'bcm_crypto': bcm_crypto_c_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700727 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700728 'crypto_headers': crypto_h_files,
729 'crypto_internal_headers': crypto_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500730 'crypto_test': sorted(crypto_test_files),
Adam Langley990a3232018-05-22 10:02:59 -0700731 'crypto_test_data': sorted('src/' + x for x in cmake['CRYPTO_TEST_DATA']),
Adam Langleyfd499932017-04-04 14:21:43 -0700732 'fips_fragments': fips_fragments,
David Benjamin38d01c62016-04-21 18:47:57 -0400733 'fuzz': fuzz_c_files,
Adam Langleyfeca9e52017-01-23 13:07:50 -0800734 'ssl': ssl_source_files,
Adam Langley049ef412015-06-09 18:20:57 -0700735 'ssl_headers': ssl_h_files,
736 'ssl_internal_headers': ssl_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500737 'ssl_test': sorted(ssl_test_files),
David Benjamin38d01c62016-04-21 18:47:57 -0400738 'tool': tool_c_files,
Adam Langleyf11f2332016-06-30 11:56:19 -0700739 'tool_headers': tool_h_files,
David Benjaminc5aa8412016-07-29 17:41:58 -0400740 'test_support': test_support_c_files,
741 'test_support_headers': test_support_h_files,
Adam Langley3e502c82019-10-16 09:56:38 -0700742 'urandom_test': sorted(urandom_test_files),
Adam Langley9e1a6602015-05-05 17:47:53 -0700743 }
744
745 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
746
Adam Langley049ef412015-06-09 18:20:57 -0700747 for platform in platforms:
748 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700749
750 return 0
751
752
Adam Langley9e1a6602015-05-05 17:47:53 -0700753if __name__ == '__main__':
Matt Braithwaite16695892016-06-09 09:34:11 -0700754 parser = optparse.OptionParser(usage='Usage: %prog [--prefix=<path>]'
David Benjamineca48e52019-08-13 11:51:53 -0400755 ' [android|android-cmake|bazel|eureka|gn|gyp]')
Matt Braithwaite16695892016-06-09 09:34:11 -0700756 parser.add_option('--prefix', dest='prefix',
757 help='For Bazel, prepend argument to all source files')
Adam Langley990a3232018-05-22 10:02:59 -0700758 parser.add_option(
759 '--embed_test_data', type='choice', dest='embed_test_data',
760 action='store', default="true", choices=["true", "false"],
David Benjaminf014d602019-05-07 18:58:06 -0500761 help='For Bazel or GN, don\'t embed data files in crypto_test_data.cc')
Matt Braithwaite16695892016-06-09 09:34:11 -0700762 options, args = parser.parse_args(sys.argv[1:])
763 PREFIX = options.prefix
Adam Langley990a3232018-05-22 10:02:59 -0700764 EMBED_TEST_DATA = (options.embed_test_data == "true")
Matt Braithwaite16695892016-06-09 09:34:11 -0700765
766 if not args:
767 parser.print_help()
768 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700769
Adam Langley049ef412015-06-09 18:20:57 -0700770 platforms = []
Matt Braithwaite16695892016-06-09 09:34:11 -0700771 for s in args:
David Benjamin38d01c62016-04-21 18:47:57 -0400772 if s == 'android':
Adam Langley049ef412015-06-09 18:20:57 -0700773 platforms.append(Android())
David Benjamineca48e52019-08-13 11:51:53 -0400774 elif s == 'android-cmake':
775 platforms.append(AndroidCMake())
Adam Langley049ef412015-06-09 18:20:57 -0700776 elif s == 'bazel':
777 platforms.append(Bazel())
Robert Sloane091af42017-10-09 12:47:17 -0700778 elif s == 'eureka':
779 platforms.append(Eureka())
David Benjamin38d01c62016-04-21 18:47:57 -0400780 elif s == 'gn':
781 platforms.append(GN())
782 elif s == 'gyp':
783 platforms.append(GYP())
Adam Langley049ef412015-06-09 18:20:57 -0700784 else:
Matt Braithwaite16695892016-06-09 09:34:11 -0700785 parser.print_help()
786 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700787
Adam Langley049ef412015-06-09 18:20:57 -0700788 sys.exit(main(platforms))