blob: 2eae98aca519bc0332f61f6ba9bdd50e161c32e6 [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):
193 with open('BUILD.generated', 'w+') as out:
194 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
Adam Langley9c164b22015-06-10 18:54:47 -0700212 with open('BUILD.generated_tests', 'w+') as out:
213 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)
220 out.write('] + glob(["src/crypto/test/*.h"])\n\n')
221
222 name_counts = {}
223 for test in files['tests']:
224 name = os.path.basename(test[0])
225 name_counts[name] = name_counts.get(name, 0) + 1
226
227 first = True
228 for test in files['tests']:
229 name = os.path.basename(test[0])
230 if name_counts[name] > 1:
231 if '/' in test[1]:
232 name += '_' + os.path.splitext(os.path.basename(test[1]))[0]
233 else:
234 name += '_' + test[1].replace('-', '_')
235
236 if not first:
237 out.write('\n')
238 first = False
239
240 src_prefix = 'src/' + test[0]
241 for src in files['test']:
242 if src.startswith(src_prefix):
243 src = src
244 break
245 else:
246 raise ValueError("Can't find source for %s" % test[0])
247
248 out.write('cc_test(\n')
249 out.write(' name = "%s",\n' % name)
250 out.write(' size = "small",\n')
251 out.write(' srcs = ["%s"] + test_support_sources,\n' % src)
252
253 data_files = []
254 if len(test) > 1:
255
256 out.write(' args = [\n')
257 for arg in test[1:]:
258 if '/' in arg:
259 out.write(' "$(location src/%s)",\n' % arg)
260 data_files.append('src/%s' % arg)
261 else:
262 out.write(' "%s",\n' % arg)
263 out.write(' ],\n')
264
265 out.write(' copts = boringssl_copts,\n')
266
267 if len(data_files) > 0:
268 out.write(' data = [\n')
269 for filename in data_files:
270 out.write(' "%s",\n' % filename)
271 out.write(' ],\n')
272
273 if 'ssl/' in test[0]:
274 out.write(' deps = [\n')
275 out.write(' ":crypto",\n')
276 out.write(' ":ssl",\n')
277 out.write(' ],\n')
278 else:
279 out.write(' deps = [":crypto"],\n')
280 out.write(')\n')
281
Adam Langley049ef412015-06-09 18:20:57 -0700282
Adam Langley9e1a6602015-05-05 17:47:53 -0700283def FindCMakeFiles(directory):
284 """Returns list of all CMakeLists.txt files recursively in directory."""
285 cmakefiles = []
286
287 for (path, _, filenames) in os.walk(directory):
288 for filename in filenames:
289 if filename == 'CMakeLists.txt':
290 cmakefiles.append(os.path.join(path, filename))
291
292 return cmakefiles
293
294
295def NoTests(dent, is_dir):
296 """Filter function that can be passed to FindCFiles in order to remove test
297 sources."""
298 if is_dir:
299 return dent != 'test'
300 return 'test.' not in dent and not dent.startswith('example_')
301
302
303def OnlyTests(dent, is_dir):
304 """Filter function that can be passed to FindCFiles in order to remove
305 non-test sources."""
306 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400307 return dent != 'test'
Adam Langley9e1a6602015-05-05 17:47:53 -0700308 return '_test.' in dent or dent.startswith('example_')
309
310
David Benjamin26073832015-05-11 20:52:48 -0400311def AllFiles(dent, is_dir):
312 """Filter function that can be passed to FindCFiles in order to include all
313 sources."""
314 return True
315
316
Adam Langley049ef412015-06-09 18:20:57 -0700317def SSLHeaderFiles(dent, is_dir):
318 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h']
319
320
Adam Langley9e1a6602015-05-05 17:47:53 -0700321def FindCFiles(directory, filter_func):
322 """Recurses through directory and returns a list of paths to all the C source
323 files that pass filter_func."""
324 cfiles = []
325
326 for (path, dirnames, filenames) in os.walk(directory):
327 for filename in filenames:
328 if not filename.endswith('.c') and not filename.endswith('.cc'):
329 continue
330 if not filter_func(filename, False):
331 continue
332 cfiles.append(os.path.join(path, filename))
333
334 for (i, dirname) in enumerate(dirnames):
335 if not filter_func(dirname, True):
336 del dirnames[i]
337
338 return cfiles
339
340
Adam Langley049ef412015-06-09 18:20:57 -0700341def FindHeaderFiles(directory, filter_func):
342 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
343 hfiles = []
344
345 for (path, dirnames, filenames) in os.walk(directory):
346 for filename in filenames:
347 if not filename.endswith('.h'):
348 continue
349 if not filter_func(filename, False):
350 continue
351 hfiles.append(os.path.join(path, filename))
352
353 return hfiles
354
355
Adam Langley9e1a6602015-05-05 17:47:53 -0700356def ExtractPerlAsmFromCMakeFile(cmakefile):
357 """Parses the contents of the CMakeLists.txt file passed as an argument and
358 returns a list of all the perlasm() directives found in the file."""
359 perlasms = []
360 with open(cmakefile) as f:
361 for line in f:
362 line = line.strip()
363 if not line.startswith('perlasm('):
364 continue
365 if not line.endswith(')'):
366 raise ValueError('Bad perlasm line in %s' % cmakefile)
367 # Remove "perlasm(" from start and ")" from end
368 params = line[8:-1].split()
369 if len(params) < 2:
370 raise ValueError('Bad perlasm line in %s' % cmakefile)
371 perlasms.append({
372 'extra_args': params[2:],
373 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
374 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
375 })
376
377 return perlasms
378
379
380def ReadPerlAsmOperations():
381 """Returns a list of all perlasm() directives found in CMake config files in
382 src/."""
383 perlasms = []
384 cmakefiles = FindCMakeFiles('src')
385
386 for cmakefile in cmakefiles:
387 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
388
389 return perlasms
390
391
392def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
393 """Runs the a perlasm script and puts the output into output_filename."""
394 base_dir = os.path.dirname(output_filename)
395 if not os.path.isdir(base_dir):
396 os.makedirs(base_dir)
397 output = subprocess.check_output(
398 ['perl', input_filename, perlasm_style] + extra_args)
399 with open(output_filename, 'w+') as out_file:
400 out_file.write(output)
401
402
403def ArchForAsmFilename(filename):
404 """Returns the architectures that a given asm file should be compiled for
405 based on substrings in the filename."""
406
407 if 'x86_64' in filename or 'avx2' in filename:
408 return ['x86_64']
409 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
410 return ['x86']
411 elif 'armx' in filename:
412 return ['arm', 'aarch64']
413 elif 'armv8' in filename:
414 return ['aarch64']
415 elif 'arm' in filename:
416 return ['arm']
417 else:
418 raise ValueError('Unknown arch for asm filename: ' + filename)
419
420
421def WriteAsmFiles(perlasms):
422 """Generates asm files from perlasm directives for each supported OS x
423 platform combination."""
424 asmfiles = {}
425
426 for osarch in OS_ARCH_COMBOS:
427 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
428 key = (osname, arch)
429 outDir = '%s-%s' % key
430
431 for perlasm in perlasms:
432 filename = os.path.basename(perlasm['input'])
433 output = perlasm['output']
434 if not output.startswith('src'):
435 raise ValueError('output missing src: %s' % output)
436 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200437 if output.endswith('-armx.${ASM_EXT}'):
438 output = output.replace('-armx',
439 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700440 output = output.replace('${ASM_EXT}', asm_ext)
441
442 if arch in ArchForAsmFilename(filename):
443 PerlAsm(output, perlasm['input'], perlasm_style,
444 perlasm['extra_args'] + extra_args)
445 asmfiles.setdefault(key, []).append(output)
446
447 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
448 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
449
450 return asmfiles
451
452
Adam Langley049ef412015-06-09 18:20:57 -0700453def main(platforms):
Adam Langley9e1a6602015-05-05 17:47:53 -0700454 crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
455 ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
456 tool_cc_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
457
458 # Generate err_data.c
459 with open('err_data.c', 'w+') as err_data:
460 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
461 cwd=os.path.join('src', 'crypto', 'err'),
462 stdout=err_data)
463 crypto_c_files.append('err_data.c')
464
David Benjamin26073832015-05-11 20:52:48 -0400465 test_support_cc_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
466 AllFiles)
467
Adam Langley9e1a6602015-05-05 17:47:53 -0700468 test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
469 test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
470
Adam Langley049ef412015-06-09 18:20:57 -0700471 ssl_h_files = (
472 FindHeaderFiles(
473 os.path.join('src', 'include', 'openssl'),
474 SSLHeaderFiles))
475
476 def NotSSLHeaderFiles(filename, is_dir):
477 return not SSLHeaderFiles(filename, is_dir)
478 crypto_h_files = (
479 FindHeaderFiles(
480 os.path.join('src', 'include', 'openssl'),
481 NotSSLHeaderFiles))
482
483 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
484 crypto_internal_h_files = FindHeaderFiles(
485 os.path.join('src', 'crypto'), NoTests)
486
Adam Langley9c164b22015-06-10 18:54:47 -0700487 with open('src/util/all_tests.json', 'r') as f:
488 tests = json.load(f)
489 test_binaries = set([test[0] for test in tests])
490 test_sources = set([
491 test.replace('.cc', '').replace('.c', '').replace(
492 'src/',
493 '')
494 for test in test_c_files])
495 if test_binaries != test_sources:
496 print 'Test sources and configured tests do not match'
497 a = test_binaries.difference(test_sources)
498 if len(a) > 0:
499 print 'These tests are configured without sources: ' + str(a)
500 b = test_sources.difference(test_binaries)
501 if len(b) > 0:
502 print 'These test sources are not configured: ' + str(b)
503
Adam Langley9e1a6602015-05-05 17:47:53 -0700504 files = {
505 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700506 'crypto_headers': crypto_h_files,
507 'crypto_internal_headers': crypto_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700508 'ssl': ssl_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700509 'ssl_headers': ssl_h_files,
510 'ssl_internal_headers': ssl_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700511 'tool': tool_cc_files,
512 'test': test_c_files,
David Benjamin26073832015-05-11 20:52:48 -0400513 'test_support': test_support_cc_files,
Adam Langley9c164b22015-06-10 18:54:47 -0700514 'tests': tests,
Adam Langley9e1a6602015-05-05 17:47:53 -0700515 }
516
517 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
518
Adam Langley049ef412015-06-09 18:20:57 -0700519 for platform in platforms:
520 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700521
522 return 0
523
524
525def Usage():
Adam Langley049ef412015-06-09 18:20:57 -0700526 print 'Usage: python %s [chromium|android|android-standalone|bazel]' % sys.argv[0]
Adam Langley9e1a6602015-05-05 17:47:53 -0700527 sys.exit(1)
528
529
530if __name__ == '__main__':
Adam Langley049ef412015-06-09 18:20:57 -0700531 if len(sys.argv) < 2:
Adam Langley9e1a6602015-05-05 17:47:53 -0700532 Usage()
533
Adam Langley049ef412015-06-09 18:20:57 -0700534 platforms = []
535 for s in sys.argv[1:]:
536 if s == 'chromium' or s == 'gyp':
537 platforms.append(Chromium())
538 elif s == 'android':
539 platforms.append(Android())
540 elif s == 'android-standalone':
541 platforms.append(AndroidStandalone())
542 elif s == 'bazel':
543 platforms.append(Bazel())
544 else:
545 Usage()
Adam Langley9e1a6602015-05-05 17:47:53 -0700546
Adam Langley049ef412015-06-09 18:20:57 -0700547 sys.exit(main(platforms))