blob: 57e5e1b146e490e586f61c93ba75352118dca17f [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'])
David Benjamin96628432017-01-19 19:05:47 -0500275
Adam Langley049ef412015-06-09 18:20:57 -0700276
Robert Sloane091af42017-10-09 12:47:17 -0700277class Eureka(object):
278
279 def __init__(self):
280 self.header = \
281"""# Copyright (C) 2017 The Android Open Source Project
282#
283# Licensed under the Apache License, Version 2.0 (the "License");
284# you may not use this file except in compliance with the License.
285# You may obtain a copy of the License at
286#
287# http://www.apache.org/licenses/LICENSE-2.0
288#
289# Unless required by applicable law or agreed to in writing, software
290# distributed under the License is distributed on an "AS IS" BASIS,
291# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
292# See the License for the specific language governing permissions and
293# limitations under the License.
294
295# This file is created by generate_build_files.py. Do not edit manually.
296
297"""
298
299 def PrintVariableSection(self, out, name, files):
300 out.write('%s := \\\n' % name)
301 for f in sorted(files):
302 out.write(' %s\\\n' % f)
303 out.write('\n')
304
305 def WriteFiles(self, files, asm_outputs):
306 # Legacy Android.mk format
307 with open('eureka.mk', 'w+') as makefile:
308 makefile.write(self.header)
309
310 self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
311 self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
312 self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
313
314 for ((osname, arch), asm_files) in asm_outputs:
315 if osname != 'linux':
316 continue
317 self.PrintVariableSection(
318 makefile, '%s_%s_sources' % (osname, arch), asm_files)
319
320
David Benjamin38d01c62016-04-21 18:47:57 -0400321class GN(object):
322
323 def __init__(self):
324 self.firstSection = True
325 self.header = \
326"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
327# Use of this source code is governed by a BSD-style license that can be
328# found in the LICENSE file.
329
330# This file is created by generate_build_files.py. Do not edit manually.
331
332"""
333
334 def PrintVariableSection(self, out, name, files):
335 if not self.firstSection:
336 out.write('\n')
337 self.firstSection = False
338
339 out.write('%s = [\n' % name)
340 for f in sorted(files):
341 out.write(' "%s",\n' % f)
342 out.write(']\n')
343
344 def WriteFiles(self, files, asm_outputs):
345 with open('BUILD.generated.gni', 'w+') as out:
346 out.write(self.header)
347
David Benjaminc5aa8412016-07-29 17:41:58 -0400348 self.PrintVariableSection(out, 'crypto_sources',
James Robinson98dd68f2018-04-11 14:47:34 -0700349 files['crypto'] +
David Benjaminc5aa8412016-07-29 17:41:58 -0400350 files['crypto_internal_headers'])
James Robinson98dd68f2018-04-11 14:47:34 -0700351 self.PrintVariableSection(out, 'crypto_headers',
352 files['crypto_headers'])
David Benjaminc5aa8412016-07-29 17:41:58 -0400353 self.PrintVariableSection(out, 'ssl_sources',
James Robinson98dd68f2018-04-11 14:47:34 -0700354 files['ssl'] + files['ssl_internal_headers'])
355 self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400356
357 for ((osname, arch), asm_files) in asm_outputs:
358 self.PrintVariableSection(
359 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
360
361 fuzzers = [os.path.splitext(os.path.basename(fuzzer))[0]
362 for fuzzer in files['fuzz']]
363 self.PrintVariableSection(out, 'fuzzers', fuzzers)
364
365 with open('BUILD.generated_tests.gni', 'w+') as out:
366 self.firstSection = True
367 out.write(self.header)
368
David Benjamin96628432017-01-19 19:05:47 -0500369 self.PrintVariableSection(out, 'test_support_sources',
David Benjaminc5aa8412016-07-29 17:41:58 -0400370 files['test_support'] +
371 files['test_support_headers'])
David Benjamin96628432017-01-19 19:05:47 -0500372 self.PrintVariableSection(out, 'crypto_test_sources',
373 files['crypto_test'])
David Benjaminf014d602019-05-07 18:58:06 -0500374 self.PrintVariableSection(out, 'crypto_test_data',
375 files['crypto_test_data'])
David Benjamin96628432017-01-19 19:05:47 -0500376 self.PrintVariableSection(out, 'ssl_test_sources', files['ssl_test'])
David Benjamin38d01c62016-04-21 18:47:57 -0400377
378
379class GYP(object):
380
381 def __init__(self):
382 self.header = \
383"""# Copyright (c) 2016 The Chromium Authors. All rights reserved.
384# Use of this source code is governed by a BSD-style license that can be
385# found in the LICENSE file.
386
387# This file is created by generate_build_files.py. Do not edit manually.
388
389"""
390
391 def PrintVariableSection(self, out, name, files):
392 out.write(' \'%s\': [\n' % name)
393 for f in sorted(files):
394 out.write(' \'%s\',\n' % f)
395 out.write(' ],\n')
396
397 def WriteFiles(self, files, asm_outputs):
398 with open('boringssl.gypi', 'w+') as gypi:
399 gypi.write(self.header + '{\n \'variables\': {\n')
400
David Benjaminc5aa8412016-07-29 17:41:58 -0400401 self.PrintVariableSection(gypi, 'boringssl_ssl_sources',
402 files['ssl'] + files['ssl_headers'] +
403 files['ssl_internal_headers'])
404 self.PrintVariableSection(gypi, 'boringssl_crypto_sources',
405 files['crypto'] + files['crypto_headers'] +
406 files['crypto_internal_headers'])
David Benjamin38d01c62016-04-21 18:47:57 -0400407
408 for ((osname, arch), asm_files) in asm_outputs:
409 self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
410 (osname, arch), asm_files)
411
412 gypi.write(' }\n}\n')
413
David Benjamin38d01c62016-04-21 18:47:57 -0400414
Adam Langley9e1a6602015-05-05 17:47:53 -0700415def FindCMakeFiles(directory):
416 """Returns list of all CMakeLists.txt files recursively in directory."""
417 cmakefiles = []
418
419 for (path, _, filenames) in os.walk(directory):
420 for filename in filenames:
421 if filename == 'CMakeLists.txt':
422 cmakefiles.append(os.path.join(path, filename))
423
424 return cmakefiles
425
Adam Langleyfd499932017-04-04 14:21:43 -0700426def OnlyFIPSFragments(path, dent, is_dir):
Matthew Braithwaite95511e92017-05-08 16:38:03 -0700427 return is_dir or (path.startswith(
428 os.path.join('src', 'crypto', 'fipsmodule', '')) and
429 NoTests(path, dent, is_dir))
Adam Langley9e1a6602015-05-05 17:47:53 -0700430
Adam Langleyfd499932017-04-04 14:21:43 -0700431def NoTestsNorFIPSFragments(path, dent, is_dir):
Adam Langley323f1eb2017-04-06 17:29:10 -0700432 return (NoTests(path, dent, is_dir) and
433 (is_dir or not OnlyFIPSFragments(path, dent, is_dir)))
Adam Langleyfd499932017-04-04 14:21:43 -0700434
435def NoTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700436 """Filter function that can be passed to FindCFiles in order to remove test
437 sources."""
438 if is_dir:
439 return dent != 'test'
David Benjamin96ee4a82017-07-09 23:46:47 -0400440 return 'test.' not in dent
Adam Langley9e1a6602015-05-05 17:47:53 -0700441
442
Adam Langleyfd499932017-04-04 14:21:43 -0700443def OnlyTests(path, dent, is_dir):
Adam Langley9e1a6602015-05-05 17:47:53 -0700444 """Filter function that can be passed to FindCFiles in order to remove
445 non-test sources."""
446 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400447 return dent != 'test'
David Benjamin96ee4a82017-07-09 23:46:47 -0400448 return '_test.' in dent
Adam Langley9e1a6602015-05-05 17:47:53 -0700449
450
Adam Langleyfd499932017-04-04 14:21:43 -0700451def AllFiles(path, dent, is_dir):
David Benjamin26073832015-05-11 20:52:48 -0400452 """Filter function that can be passed to FindCFiles in order to include all
453 sources."""
454 return True
455
456
Adam Langleyfd499932017-04-04 14:21:43 -0700457def NoTestRunnerFiles(path, dent, is_dir):
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700458 """Filter function that can be passed to FindCFiles or FindHeaderFiles in
459 order to exclude test runner files."""
460 # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
461 # are in their own subpackage, from being included in boringssl/BUILD files.
462 return not is_dir or dent != 'runner'
463
464
David Benjamin3ecd0a52017-05-19 15:26:18 -0400465def NotGTestSupport(path, dent, is_dir):
David Benjaminc3889632019-03-01 15:03:05 -0500466 return 'gtest' not in dent and 'abi_test' not in dent
David Benjamin96628432017-01-19 19:05:47 -0500467
468
Adam Langleyfd499932017-04-04 14:21:43 -0700469def SSLHeaderFiles(path, dent, is_dir):
Aaron Green0e150022018-10-16 12:05:29 -0700470 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h', 'srtp.h']
Adam Langley049ef412015-06-09 18:20:57 -0700471
472
Adam Langley9e1a6602015-05-05 17:47:53 -0700473def FindCFiles(directory, filter_func):
474 """Recurses through directory and returns a list of paths to all the C source
475 files that pass filter_func."""
476 cfiles = []
477
478 for (path, dirnames, filenames) in os.walk(directory):
479 for filename in filenames:
480 if not filename.endswith('.c') and not filename.endswith('.cc'):
481 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700482 if not filter_func(path, filename, False):
Adam Langley9e1a6602015-05-05 17:47:53 -0700483 continue
484 cfiles.append(os.path.join(path, filename))
485
486 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700487 if not filter_func(path, dirname, True):
Adam Langley9e1a6602015-05-05 17:47:53 -0700488 del dirnames[i]
489
490 return cfiles
491
492
Adam Langley049ef412015-06-09 18:20:57 -0700493def FindHeaderFiles(directory, filter_func):
494 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
495 hfiles = []
496
497 for (path, dirnames, filenames) in os.walk(directory):
498 for filename in filenames:
499 if not filename.endswith('.h'):
500 continue
Adam Langleyfd499932017-04-04 14:21:43 -0700501 if not filter_func(path, filename, False):
Adam Langley049ef412015-06-09 18:20:57 -0700502 continue
503 hfiles.append(os.path.join(path, filename))
504
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700505 for (i, dirname) in enumerate(dirnames):
Adam Langleyfd499932017-04-04 14:21:43 -0700506 if not filter_func(path, dirname, True):
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700507 del dirnames[i]
508
Adam Langley049ef412015-06-09 18:20:57 -0700509 return hfiles
510
511
Adam Langley9e1a6602015-05-05 17:47:53 -0700512def ExtractPerlAsmFromCMakeFile(cmakefile):
513 """Parses the contents of the CMakeLists.txt file passed as an argument and
514 returns a list of all the perlasm() directives found in the file."""
515 perlasms = []
516 with open(cmakefile) as f:
517 for line in f:
518 line = line.strip()
519 if not line.startswith('perlasm('):
520 continue
521 if not line.endswith(')'):
522 raise ValueError('Bad perlasm line in %s' % cmakefile)
523 # Remove "perlasm(" from start and ")" from end
524 params = line[8:-1].split()
525 if len(params) < 2:
526 raise ValueError('Bad perlasm line in %s' % cmakefile)
527 perlasms.append({
528 'extra_args': params[2:],
529 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
530 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
531 })
532
533 return perlasms
534
535
536def ReadPerlAsmOperations():
537 """Returns a list of all perlasm() directives found in CMake config files in
538 src/."""
539 perlasms = []
540 cmakefiles = FindCMakeFiles('src')
541
542 for cmakefile in cmakefiles:
543 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
544
545 return perlasms
546
547
548def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
549 """Runs the a perlasm script and puts the output into output_filename."""
550 base_dir = os.path.dirname(output_filename)
551 if not os.path.isdir(base_dir):
552 os.makedirs(base_dir)
David Benjaminfdd8e9c2016-06-26 13:18:50 -0400553 subprocess.check_call(
554 ['perl', input_filename, perlasm_style] + extra_args + [output_filename])
Adam Langley9e1a6602015-05-05 17:47:53 -0700555
556
557def ArchForAsmFilename(filename):
558 """Returns the architectures that a given asm file should be compiled for
559 based on substrings in the filename."""
560
561 if 'x86_64' in filename or 'avx2' in filename:
562 return ['x86_64']
563 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
564 return ['x86']
565 elif 'armx' in filename:
566 return ['arm', 'aarch64']
567 elif 'armv8' in filename:
568 return ['aarch64']
569 elif 'arm' in filename:
570 return ['arm']
David Benjamin9f16ce12016-09-27 16:30:22 -0400571 elif 'ppc' in filename:
572 return ['ppc64le']
Adam Langley9e1a6602015-05-05 17:47:53 -0700573 else:
574 raise ValueError('Unknown arch for asm filename: ' + filename)
575
576
577def WriteAsmFiles(perlasms):
578 """Generates asm files from perlasm directives for each supported OS x
579 platform combination."""
580 asmfiles = {}
581
582 for osarch in OS_ARCH_COMBOS:
583 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
584 key = (osname, arch)
585 outDir = '%s-%s' % key
586
587 for perlasm in perlasms:
588 filename = os.path.basename(perlasm['input'])
589 output = perlasm['output']
590 if not output.startswith('src'):
591 raise ValueError('output missing src: %s' % output)
592 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200593 if output.endswith('-armx.${ASM_EXT}'):
594 output = output.replace('-armx',
595 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700596 output = output.replace('${ASM_EXT}', asm_ext)
597
598 if arch in ArchForAsmFilename(filename):
599 PerlAsm(output, perlasm['input'], perlasm_style,
600 perlasm['extra_args'] + extra_args)
601 asmfiles.setdefault(key, []).append(output)
602
603 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
604 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
605
606 return asmfiles
607
608
David Benjamin3ecd0a52017-05-19 15:26:18 -0400609def ExtractVariablesFromCMakeFile(cmakefile):
610 """Parses the contents of the CMakeLists.txt file passed as an argument and
611 returns a dictionary of exported source lists."""
612 variables = {}
613 in_set_command = False
614 set_command = []
615 with open(cmakefile) as f:
616 for line in f:
617 if '#' in line:
618 line = line[:line.index('#')]
619 line = line.strip()
620
621 if not in_set_command:
622 if line.startswith('set('):
623 in_set_command = True
624 set_command = []
625 elif line == ')':
626 in_set_command = False
627 if not set_command:
628 raise ValueError('Empty set command')
629 variables[set_command[0]] = set_command[1:]
630 else:
631 set_command.extend([c for c in line.split(' ') if c])
632
633 if in_set_command:
634 raise ValueError('Unfinished set command')
635 return variables
636
637
Adam Langley049ef412015-06-09 18:20:57 -0700638def main(platforms):
David Benjamin3ecd0a52017-05-19 15:26:18 -0400639 cmake = ExtractVariablesFromCMakeFile(os.path.join('src', 'sources.cmake'))
Andres Erbsen5b280a82017-10-30 15:58:33 +0000640 crypto_c_files = (FindCFiles(os.path.join('src', 'crypto'), NoTestsNorFIPSFragments) +
Adam Langleye0c533a2019-05-20 09:50:07 -0700641 FindCFiles(os.path.join('src', 'third_party', 'fiat'), NoTestsNorFIPSFragments) +
642 FindCFiles(os.path.join('src', 'third_party', 'sike'), NoTestsNorFIPSFragments))
Adam Langleyfd499932017-04-04 14:21:43 -0700643 fips_fragments = FindCFiles(os.path.join('src', 'crypto', 'fipsmodule'), OnlyFIPSFragments)
Adam Langleyfeca9e52017-01-23 13:07:50 -0800644 ssl_source_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
David Benjamin38d01c62016-04-21 18:47:57 -0400645 tool_c_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
Adam Langleyf11f2332016-06-30 11:56:19 -0700646 tool_h_files = FindHeaderFiles(os.path.join('src', 'tool'), AllFiles)
Adam Langley9e1a6602015-05-05 17:47:53 -0700647
David Benjamin0c9c1aa2017-12-12 15:19:20 -0500648 # third_party/fiat/p256.c lives in third_party/fiat, but it is a FIPS
649 # fragment, not a normal source file.
650 p256 = os.path.join('src', 'third_party', 'fiat', 'p256.c')
651 fips_fragments.append(p256)
652 crypto_c_files.remove(p256)
653
Pete Bentley44544d92019-08-15 15:01:26 +0100654 # BCM shared library C files
655 bcm_crypto_c_files = [
656 os.path.join('src', 'crypto', 'fipsmodule', 'bcm.c')
657 ]
658
Adam Langley9e1a6602015-05-05 17:47:53 -0700659 # Generate err_data.c
660 with open('err_data.c', 'w+') as err_data:
661 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
662 cwd=os.path.join('src', 'crypto', 'err'),
663 stdout=err_data)
664 crypto_c_files.append('err_data.c')
665
David Benjamin38d01c62016-04-21 18:47:57 -0400666 test_support_c_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
David Benjamin3ecd0a52017-05-19 15:26:18 -0400667 NotGTestSupport)
Matt Braithwaitedfdd49c2016-06-13 17:06:48 -0700668 test_support_h_files = (
669 FindHeaderFiles(os.path.join('src', 'crypto', 'test'), AllFiles) +
Martin Kreichgauer8b487b72017-04-03 16:07:27 -0700670 FindHeaderFiles(os.path.join('src', 'ssl', 'test'), NoTestRunnerFiles))
David Benjamin26073832015-05-11 20:52:48 -0400671
Adam Langley990a3232018-05-22 10:02:59 -0700672 crypto_test_files = []
673 if EMBED_TEST_DATA:
674 # Generate crypto_test_data.cc
675 with open('crypto_test_data.cc', 'w+') as out:
676 subprocess.check_call(
677 ['go', 'run', 'util/embed_test_data.go'] + cmake['CRYPTO_TEST_DATA'],
678 cwd='src',
679 stdout=out)
680 crypto_test_files += ['crypto_test_data.cc']
David Benjamin3ecd0a52017-05-19 15:26:18 -0400681
Adam Langley990a3232018-05-22 10:02:59 -0700682 crypto_test_files += FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
David Benjamin96ee4a82017-07-09 23:46:47 -0400683 crypto_test_files += [
David Benjaminc3889632019-03-01 15:03:05 -0500684 'src/crypto/test/abi_test.cc',
David Benjamin3ecd0a52017-05-19 15:26:18 -0400685 'src/crypto/test/file_test_gtest.cc',
686 'src/crypto/test/gtest_main.cc',
687 ]
David Benjamin1d5a5702017-02-13 22:11:49 -0500688
689 ssl_test_files = FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
Robert Sloanae1e0872019-03-01 16:01:30 -0800690 ssl_test_files += [
691 'src/crypto/test/abi_test.cc',
692 'src/crypto/test/gtest_main.cc',
693 ]
Adam Langley9e1a6602015-05-05 17:47:53 -0700694
David Benjamin38d01c62016-04-21 18:47:57 -0400695 fuzz_c_files = FindCFiles(os.path.join('src', 'fuzz'), NoTests)
696
Adam Langley049ef412015-06-09 18:20:57 -0700697 ssl_h_files = (
698 FindHeaderFiles(
699 os.path.join('src', 'include', 'openssl'),
700 SSLHeaderFiles))
701
Adam Langleyfd499932017-04-04 14:21:43 -0700702 def NotSSLHeaderFiles(path, filename, is_dir):
703 return not SSLHeaderFiles(path, filename, is_dir)
Adam Langley049ef412015-06-09 18:20:57 -0700704 crypto_h_files = (
705 FindHeaderFiles(
706 os.path.join('src', 'include', 'openssl'),
707 NotSSLHeaderFiles))
708
709 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
Andres Erbsen5b280a82017-10-30 15:58:33 +0000710 crypto_internal_h_files = (
711 FindHeaderFiles(os.path.join('src', 'crypto'), NoTests) +
Adam Langleye0c533a2019-05-20 09:50:07 -0700712 FindHeaderFiles(os.path.join('src', 'third_party', 'fiat'), NoTests) +
713 FindHeaderFiles(os.path.join('src', 'third_party', 'sike'), NoTests))
Adam Langley049ef412015-06-09 18:20:57 -0700714
Adam Langley9e1a6602015-05-05 17:47:53 -0700715 files = {
Pete Bentley44544d92019-08-15 15:01:26 +0100716 'bcm_crypto': bcm_crypto_c_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700717 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700718 'crypto_headers': crypto_h_files,
719 'crypto_internal_headers': crypto_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500720 'crypto_test': sorted(crypto_test_files),
Adam Langley990a3232018-05-22 10:02:59 -0700721 'crypto_test_data': sorted('src/' + x for x in cmake['CRYPTO_TEST_DATA']),
Adam Langleyfd499932017-04-04 14:21:43 -0700722 'fips_fragments': fips_fragments,
David Benjamin38d01c62016-04-21 18:47:57 -0400723 'fuzz': fuzz_c_files,
Adam Langleyfeca9e52017-01-23 13:07:50 -0800724 'ssl': ssl_source_files,
Adam Langley049ef412015-06-09 18:20:57 -0700725 'ssl_headers': ssl_h_files,
726 'ssl_internal_headers': ssl_internal_h_files,
David Benjamin1d5a5702017-02-13 22:11:49 -0500727 'ssl_test': sorted(ssl_test_files),
David Benjamin38d01c62016-04-21 18:47:57 -0400728 'tool': tool_c_files,
Adam Langleyf11f2332016-06-30 11:56:19 -0700729 'tool_headers': tool_h_files,
David Benjaminc5aa8412016-07-29 17:41:58 -0400730 'test_support': test_support_c_files,
731 'test_support_headers': test_support_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700732 }
733
734 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
735
Adam Langley049ef412015-06-09 18:20:57 -0700736 for platform in platforms:
737 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700738
739 return 0
740
741
Adam Langley9e1a6602015-05-05 17:47:53 -0700742if __name__ == '__main__':
Matt Braithwaite16695892016-06-09 09:34:11 -0700743 parser = optparse.OptionParser(usage='Usage: %prog [--prefix=<path>]'
David Benjamineca48e52019-08-13 11:51:53 -0400744 ' [android|android-cmake|bazel|eureka|gn|gyp]')
Matt Braithwaite16695892016-06-09 09:34:11 -0700745 parser.add_option('--prefix', dest='prefix',
746 help='For Bazel, prepend argument to all source files')
Adam Langley990a3232018-05-22 10:02:59 -0700747 parser.add_option(
748 '--embed_test_data', type='choice', dest='embed_test_data',
749 action='store', default="true", choices=["true", "false"],
David Benjaminf014d602019-05-07 18:58:06 -0500750 help='For Bazel or GN, don\'t embed data files in crypto_test_data.cc')
Matt Braithwaite16695892016-06-09 09:34:11 -0700751 options, args = parser.parse_args(sys.argv[1:])
752 PREFIX = options.prefix
Adam Langley990a3232018-05-22 10:02:59 -0700753 EMBED_TEST_DATA = (options.embed_test_data == "true")
Matt Braithwaite16695892016-06-09 09:34:11 -0700754
755 if not args:
756 parser.print_help()
757 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700758
Adam Langley049ef412015-06-09 18:20:57 -0700759 platforms = []
Matt Braithwaite16695892016-06-09 09:34:11 -0700760 for s in args:
David Benjamin38d01c62016-04-21 18:47:57 -0400761 if s == 'android':
Adam Langley049ef412015-06-09 18:20:57 -0700762 platforms.append(Android())
David Benjamineca48e52019-08-13 11:51:53 -0400763 elif s == 'android-cmake':
764 platforms.append(AndroidCMake())
Adam Langley049ef412015-06-09 18:20:57 -0700765 elif s == 'bazel':
766 platforms.append(Bazel())
Robert Sloane091af42017-10-09 12:47:17 -0700767 elif s == 'eureka':
768 platforms.append(Eureka())
David Benjamin38d01c62016-04-21 18:47:57 -0400769 elif s == 'gn':
770 platforms.append(GN())
771 elif s == 'gyp':
772 platforms.append(GYP())
Adam Langley049ef412015-06-09 18:20:57 -0700773 else:
Matt Braithwaite16695892016-06-09 09:34:11 -0700774 parser.print_help()
775 sys.exit(1)
Adam Langley9e1a6602015-05-05 17:47:53 -0700776
Adam Langley049ef412015-06-09 18:20:57 -0700777 sys.exit(main(platforms))