blob: 9254590a9e3aee483e13b9e824fb97eb1e7d0103 [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
15"""Enumerates the BoringSSL source in src/ and either generates two gypi files
16 (boringssl.gypi and boringssl_tests.gypi) for Chromium, or generates
17 source-list files for Android."""
18
19import os
20import subprocess
21import sys
Adam Langley9c164b22015-06-10 18:54:47 -070022import json
Adam Langley9e1a6602015-05-05 17:47:53 -070023
24
25# OS_ARCH_COMBOS maps from OS and platform to the OpenSSL assembly "style" for
26# that platform and the extension used by asm files.
27OS_ARCH_COMBOS = [
28 ('linux', 'arm', 'linux32', [], 'S'),
29 ('linux', 'aarch64', 'linux64', [], 'S'),
30 ('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'): [
42 'src/crypto/poly1305/poly1305_arm_asm.S',
43 'src/crypto/chacha/chacha_vec_arm.S',
44 'src/crypto/cpu-arm-asm.S',
45 ],
46}
47
48
49class Chromium(object):
50
51 def __init__(self):
52 self.header = \
53"""# Copyright (c) 2014 The Chromium Authors. All rights reserved.
54# Use of this source code is governed by a BSD-style license that can be
55# found in the LICENSE file.
56
57# This file is created by generate_build_files.py. Do not edit manually.
58
59"""
60
61 def PrintVariableSection(self, out, name, files):
62 out.write(' \'%s\': [\n' % name)
63 for f in sorted(files):
64 out.write(' \'%s\',\n' % f)
65 out.write(' ],\n')
66
67 def WriteFiles(self, files, asm_outputs):
68 with open('boringssl.gypi', 'w+') as gypi:
69 gypi.write(self.header + '{\n \'variables\': {\n')
70
71 self.PrintVariableSection(
Adam Langley049ef412015-06-09 18:20:57 -070072 gypi, 'boringssl_ssl_sources', files['ssl'])
73 self.PrintVariableSection(
74 gypi, 'boringssl_crypto_sources', files['crypto'])
Adam Langley9e1a6602015-05-05 17:47:53 -070075
76 for ((osname, arch), asm_files) in asm_outputs:
77 self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
78 (osname, arch), asm_files)
79
80 gypi.write(' }\n}\n')
81
82 with open('boringssl_tests.gypi', 'w+') as test_gypi:
83 test_gypi.write(self.header + '{\n \'targets\': [\n')
84
85 test_names = []
86 for test in sorted(files['test']):
87 test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
88 test_gypi.write(""" {
89 'target_name': '%s',
90 'type': 'executable',
91 'dependencies': [
92 'boringssl.gyp:boringssl',
93 ],
94 'sources': [
95 '%s',
David Benjamin26073832015-05-11 20:52:48 -040096 '<@(boringssl_test_support_sources)',
Adam Langley9e1a6602015-05-05 17:47:53 -070097 ],
98 # TODO(davidben): Fix size_t truncations in BoringSSL.
99 # https://crbug.com/429039
100 'msvs_disabled_warnings': [ 4267, ],
101 },\n""" % (test_name, test))
102 test_names.append(test_name)
103
104 test_names.sort()
105
David Benjamin26073832015-05-11 20:52:48 -0400106 test_gypi.write(' ],\n \'variables\': {\n')
107
108 self.PrintVariableSection(
109 test_gypi, 'boringssl_test_support_sources', files['test_support'])
110
111 test_gypi.write(' \'boringssl_test_targets\': [\n')
Adam Langley9e1a6602015-05-05 17:47:53 -0700112
113 for test in test_names:
114 test_gypi.write(""" '%s',\n""" % test)
115
116 test_gypi.write(' ],\n }\n}\n')
117
118
119class Android(object):
120
121 def __init__(self):
122 self.header = \
123"""# Copyright (C) 2015 The Android Open Source Project
124#
125# Licensed under the Apache License, Version 2.0 (the "License");
126# you may not use this file except in compliance with the License.
127# You may obtain a copy of the License at
128#
129# http://www.apache.org/licenses/LICENSE-2.0
130#
131# Unless required by applicable law or agreed to in writing, software
132# distributed under the License is distributed on an "AS IS" BASIS,
133# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
134# See the License for the specific language governing permissions and
135# limitations under the License.
136
137"""
138
Adam Langley049ef412015-06-09 18:20:57 -0700139 def ExtraFiles(self):
140 return ['android_compat_hacks.c', 'android_compat_keywrap.c']
141
Adam Langley9e1a6602015-05-05 17:47:53 -0700142 def PrintVariableSection(self, out, name, files):
143 out.write('%s := \\\n' % name)
144 for f in sorted(files):
145 out.write(' %s\\\n' % f)
146 out.write('\n')
147
148 def WriteFiles(self, files, asm_outputs):
149 with open('sources.mk', 'w+') as makefile:
150 makefile.write(self.header)
151
Adam Langley049ef412015-06-09 18:20:57 -0700152 files['crypto'].extend(self.ExtraFiles())
Adam Langley9e1a6602015-05-05 17:47:53 -0700153 self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
154 self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
155 self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
156
157 for ((osname, arch), asm_files) in asm_outputs:
158 self.PrintVariableSection(
159 makefile, '%s_%s_sources' % (osname, arch), asm_files)
160
161
Adam Langley049ef412015-06-09 18:20:57 -0700162class AndroidStandalone(Android):
163 """AndroidStandalone is for Android builds outside of the Android-system, i.e.
164
165 for applications that wish wish to ship BoringSSL.
166 """
167
168 def ExtraFiles(self):
169 return []
170
171
172class Bazel(object):
173 """Bazel outputs files suitable for including in Bazel files."""
174
175 def __init__(self):
176 self.firstSection = True
177 self.header = \
178"""# This file is created by generate_build_files.py. Do not edit manually.
179
180"""
181
182 def PrintVariableSection(self, out, name, files):
183 if not self.firstSection:
184 out.write('\n')
185 self.firstSection = False
186
187 out.write('%s = [\n' % name)
188 for f in sorted(files):
189 out.write(' "%s",\n' % f)
190 out.write(']\n')
191
192 def WriteFiles(self, files, asm_outputs):
Chuck Haysc608d6b2015-10-06 17:54:16 -0700193 with open('BUILD.generated.bzl', 'w+') as out:
Adam Langley049ef412015-06-09 18:20:57 -0700194 out.write(self.header)
195
196 self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
197 self.PrintVariableSection(
198 out, 'ssl_internal_headers', files['ssl_internal_headers'])
199 self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
200 self.PrintVariableSection(out, 'crypto_headers', files['crypto_headers'])
201 self.PrintVariableSection(
202 out, 'crypto_internal_headers', files['crypto_internal_headers'])
203 self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
204 self.PrintVariableSection(out, 'tool_sources', files['tool'])
205
206 for ((osname, arch), asm_files) in asm_outputs:
207 if osname is not 'linux':
208 continue
209 self.PrintVariableSection(
210 out, 'crypto_sources_%s' % arch, asm_files)
211
Chuck Haysc608d6b2015-10-06 17:54:16 -0700212 with open('BUILD.generated_tests.bzl', 'w+') as out:
Adam Langley9c164b22015-06-10 18:54:47 -0700213 out.write(self.header)
214
215 out.write('test_support_sources = [\n')
216 for filename in files['test_support']:
217 if os.path.basename(filename) == 'malloc.cc':
218 continue
219 out.write(' "%s",\n' % filename)
Adam Langley9c164b22015-06-10 18:54:47 -0700220
Chuck Haysc608d6b2015-10-06 17:54:16 -0700221 out.write(']\n\n')
222
223 out.write('def create_tests(copts):\n')
224 out.write(' test_support_sources_complete = test_support_sources + \\\n')
225 out.write(' native.glob(["src/crypto/test/*.h"])\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700226 name_counts = {}
227 for test in files['tests']:
228 name = os.path.basename(test[0])
229 name_counts[name] = name_counts.get(name, 0) + 1
230
231 first = True
232 for test in files['tests']:
233 name = os.path.basename(test[0])
234 if name_counts[name] > 1:
235 if '/' in test[1]:
236 name += '_' + os.path.splitext(os.path.basename(test[1]))[0]
237 else:
238 name += '_' + test[1].replace('-', '_')
239
240 if not first:
241 out.write('\n')
242 first = False
243
244 src_prefix = 'src/' + test[0]
245 for src in files['test']:
246 if src.startswith(src_prefix):
247 src = src
248 break
249 else:
250 raise ValueError("Can't find source for %s" % test[0])
251
Chuck Haysc608d6b2015-10-06 17:54:16 -0700252 out.write(' native.cc_test(\n')
253 out.write(' name = "%s",\n' % name)
254 out.write(' size = "small",\n')
255 out.write(' srcs = ["%s"] + test_support_sources_complete,\n' % src)
Adam Langley9c164b22015-06-10 18:54:47 -0700256
257 data_files = []
258 if len(test) > 1:
259
Chuck Haysc608d6b2015-10-06 17:54:16 -0700260 out.write(' args = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700261 for arg in test[1:]:
262 if '/' in arg:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700263 out.write(' "$(location src/%s)",\n' % arg)
Adam Langley9c164b22015-06-10 18:54:47 -0700264 data_files.append('src/%s' % arg)
265 else:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700266 out.write(' "%s",\n' % arg)
267 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700268
Chuck Haysc608d6b2015-10-06 17:54:16 -0700269 out.write(' copts = copts,\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700270
271 if len(data_files) > 0:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700272 out.write(' data = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700273 for filename in data_files:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700274 out.write(' "%s",\n' % filename)
275 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700276
277 if 'ssl/' in test[0]:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700278 out.write(' deps = [\n')
279 out.write(' ":crypto",\n')
280 out.write(' ":ssl",\n')
281 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700282 else:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700283 out.write(' deps = [":crypto"],\n')
284 out.write(' )\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700285
Adam Langley049ef412015-06-09 18:20:57 -0700286
Adam Langley9e1a6602015-05-05 17:47:53 -0700287def FindCMakeFiles(directory):
288 """Returns list of all CMakeLists.txt files recursively in directory."""
289 cmakefiles = []
290
291 for (path, _, filenames) in os.walk(directory):
292 for filename in filenames:
293 if filename == 'CMakeLists.txt':
294 cmakefiles.append(os.path.join(path, filename))
295
296 return cmakefiles
297
298
299def NoTests(dent, is_dir):
300 """Filter function that can be passed to FindCFiles in order to remove test
301 sources."""
302 if is_dir:
303 return dent != 'test'
304 return 'test.' not in dent and not dent.startswith('example_')
305
306
307def OnlyTests(dent, is_dir):
308 """Filter function that can be passed to FindCFiles in order to remove
309 non-test sources."""
310 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400311 return dent != 'test'
Adam Langley9e1a6602015-05-05 17:47:53 -0700312 return '_test.' in dent or dent.startswith('example_')
313
314
David Benjamin26073832015-05-11 20:52:48 -0400315def AllFiles(dent, is_dir):
316 """Filter function that can be passed to FindCFiles in order to include all
317 sources."""
318 return True
319
320
Adam Langley049ef412015-06-09 18:20:57 -0700321def SSLHeaderFiles(dent, is_dir):
322 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h']
323
324
Adam Langley9e1a6602015-05-05 17:47:53 -0700325def FindCFiles(directory, filter_func):
326 """Recurses through directory and returns a list of paths to all the C source
327 files that pass filter_func."""
328 cfiles = []
329
330 for (path, dirnames, filenames) in os.walk(directory):
331 for filename in filenames:
332 if not filename.endswith('.c') and not filename.endswith('.cc'):
333 continue
334 if not filter_func(filename, False):
335 continue
336 cfiles.append(os.path.join(path, filename))
337
338 for (i, dirname) in enumerate(dirnames):
339 if not filter_func(dirname, True):
340 del dirnames[i]
341
342 return cfiles
343
344
Adam Langley049ef412015-06-09 18:20:57 -0700345def FindHeaderFiles(directory, filter_func):
346 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
347 hfiles = []
348
349 for (path, dirnames, filenames) in os.walk(directory):
350 for filename in filenames:
351 if not filename.endswith('.h'):
352 continue
353 if not filter_func(filename, False):
354 continue
355 hfiles.append(os.path.join(path, filename))
356
357 return hfiles
358
359
Adam Langley9e1a6602015-05-05 17:47:53 -0700360def ExtractPerlAsmFromCMakeFile(cmakefile):
361 """Parses the contents of the CMakeLists.txt file passed as an argument and
362 returns a list of all the perlasm() directives found in the file."""
363 perlasms = []
364 with open(cmakefile) as f:
365 for line in f:
366 line = line.strip()
367 if not line.startswith('perlasm('):
368 continue
369 if not line.endswith(')'):
370 raise ValueError('Bad perlasm line in %s' % cmakefile)
371 # Remove "perlasm(" from start and ")" from end
372 params = line[8:-1].split()
373 if len(params) < 2:
374 raise ValueError('Bad perlasm line in %s' % cmakefile)
375 perlasms.append({
376 'extra_args': params[2:],
377 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
378 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
379 })
380
381 return perlasms
382
383
384def ReadPerlAsmOperations():
385 """Returns a list of all perlasm() directives found in CMake config files in
386 src/."""
387 perlasms = []
388 cmakefiles = FindCMakeFiles('src')
389
390 for cmakefile in cmakefiles:
391 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
392
393 return perlasms
394
395
396def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
397 """Runs the a perlasm script and puts the output into output_filename."""
398 base_dir = os.path.dirname(output_filename)
399 if not os.path.isdir(base_dir):
400 os.makedirs(base_dir)
401 output = subprocess.check_output(
402 ['perl', input_filename, perlasm_style] + extra_args)
403 with open(output_filename, 'w+') as out_file:
404 out_file.write(output)
405
406
407def ArchForAsmFilename(filename):
408 """Returns the architectures that a given asm file should be compiled for
409 based on substrings in the filename."""
410
411 if 'x86_64' in filename or 'avx2' in filename:
412 return ['x86_64']
413 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
414 return ['x86']
415 elif 'armx' in filename:
416 return ['arm', 'aarch64']
417 elif 'armv8' in filename:
418 return ['aarch64']
419 elif 'arm' in filename:
420 return ['arm']
421 else:
422 raise ValueError('Unknown arch for asm filename: ' + filename)
423
424
425def WriteAsmFiles(perlasms):
426 """Generates asm files from perlasm directives for each supported OS x
427 platform combination."""
428 asmfiles = {}
429
430 for osarch in OS_ARCH_COMBOS:
431 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
432 key = (osname, arch)
433 outDir = '%s-%s' % key
434
435 for perlasm in perlasms:
436 filename = os.path.basename(perlasm['input'])
437 output = perlasm['output']
438 if not output.startswith('src'):
439 raise ValueError('output missing src: %s' % output)
440 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200441 if output.endswith('-armx.${ASM_EXT}'):
442 output = output.replace('-armx',
443 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700444 output = output.replace('${ASM_EXT}', asm_ext)
445
446 if arch in ArchForAsmFilename(filename):
447 PerlAsm(output, perlasm['input'], perlasm_style,
448 perlasm['extra_args'] + extra_args)
449 asmfiles.setdefault(key, []).append(output)
450
451 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
452 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
453
454 return asmfiles
455
456
Adam Langley049ef412015-06-09 18:20:57 -0700457def main(platforms):
Adam Langley9e1a6602015-05-05 17:47:53 -0700458 crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
459 ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
460 tool_cc_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
461
462 # Generate err_data.c
463 with open('err_data.c', 'w+') as err_data:
464 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
465 cwd=os.path.join('src', 'crypto', 'err'),
466 stdout=err_data)
467 crypto_c_files.append('err_data.c')
468
David Benjamin26073832015-05-11 20:52:48 -0400469 test_support_cc_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
470 AllFiles)
471
Adam Langley9e1a6602015-05-05 17:47:53 -0700472 test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
473 test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
474
Adam Langley049ef412015-06-09 18:20:57 -0700475 ssl_h_files = (
476 FindHeaderFiles(
477 os.path.join('src', 'include', 'openssl'),
478 SSLHeaderFiles))
479
480 def NotSSLHeaderFiles(filename, is_dir):
481 return not SSLHeaderFiles(filename, is_dir)
482 crypto_h_files = (
483 FindHeaderFiles(
484 os.path.join('src', 'include', 'openssl'),
485 NotSSLHeaderFiles))
486
487 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
488 crypto_internal_h_files = FindHeaderFiles(
489 os.path.join('src', 'crypto'), NoTests)
490
Adam Langley9c164b22015-06-10 18:54:47 -0700491 with open('src/util/all_tests.json', 'r') as f:
492 tests = json.load(f)
493 test_binaries = set([test[0] for test in tests])
494 test_sources = set([
495 test.replace('.cc', '').replace('.c', '').replace(
496 'src/',
497 '')
498 for test in test_c_files])
499 if test_binaries != test_sources:
500 print 'Test sources and configured tests do not match'
501 a = test_binaries.difference(test_sources)
502 if len(a) > 0:
503 print 'These tests are configured without sources: ' + str(a)
504 b = test_sources.difference(test_binaries)
505 if len(b) > 0:
506 print 'These test sources are not configured: ' + str(b)
507
Adam Langley9e1a6602015-05-05 17:47:53 -0700508 files = {
509 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700510 'crypto_headers': crypto_h_files,
511 'crypto_internal_headers': crypto_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700512 'ssl': ssl_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700513 'ssl_headers': ssl_h_files,
514 'ssl_internal_headers': ssl_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700515 'tool': tool_cc_files,
516 'test': test_c_files,
David Benjamin26073832015-05-11 20:52:48 -0400517 'test_support': test_support_cc_files,
Adam Langley9c164b22015-06-10 18:54:47 -0700518 'tests': tests,
Adam Langley9e1a6602015-05-05 17:47:53 -0700519 }
520
521 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
522
Adam Langley049ef412015-06-09 18:20:57 -0700523 for platform in platforms:
524 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700525
526 return 0
527
528
529def Usage():
Adam Langley049ef412015-06-09 18:20:57 -0700530 print 'Usage: python %s [chromium|android|android-standalone|bazel]' % sys.argv[0]
Adam Langley9e1a6602015-05-05 17:47:53 -0700531 sys.exit(1)
532
533
534if __name__ == '__main__':
Adam Langley049ef412015-06-09 18:20:57 -0700535 if len(sys.argv) < 2:
Adam Langley9e1a6602015-05-05 17:47:53 -0700536 Usage()
537
Adam Langley049ef412015-06-09 18:20:57 -0700538 platforms = []
539 for s in sys.argv[1:]:
540 if s == 'chromium' or s == 'gyp':
541 platforms.append(Chromium())
542 elif s == 'android':
543 platforms.append(Android())
544 elif s == 'android-standalone':
545 platforms.append(AndroidStandalone())
546 elif s == 'bazel':
547 platforms.append(Bazel())
548 else:
549 Usage()
Adam Langley9e1a6602015-05-05 17:47:53 -0700550
Adam Langley049ef412015-06-09 18:20:57 -0700551 sys.exit(main(platforms))