blob: 856960e4b8e787d20c8d9332e9b2eb62bfa8864a [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:
Adam Langley049ef412015-06-09 18:20:57 -0700207 self.PrintVariableSection(
Piotr Sikora3f5fe602015-10-28 12:24:35 -0700208 out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
Adam Langley049ef412015-06-09 18:20:57 -0700209
Chuck Haysc608d6b2015-10-06 17:54:16 -0700210 with open('BUILD.generated_tests.bzl', 'w+') as out:
Adam Langley9c164b22015-06-10 18:54:47 -0700211 out.write(self.header)
212
213 out.write('test_support_sources = [\n')
214 for filename in files['test_support']:
215 if os.path.basename(filename) == 'malloc.cc':
216 continue
217 out.write(' "%s",\n' % filename)
Adam Langley9c164b22015-06-10 18:54:47 -0700218
Chuck Haysc608d6b2015-10-06 17:54:16 -0700219 out.write(']\n\n')
220
221 out.write('def create_tests(copts):\n')
222 out.write(' test_support_sources_complete = test_support_sources + \\\n')
223 out.write(' native.glob(["src/crypto/test/*.h"])\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700224 name_counts = {}
225 for test in files['tests']:
226 name = os.path.basename(test[0])
227 name_counts[name] = name_counts.get(name, 0) + 1
228
229 first = True
230 for test in files['tests']:
231 name = os.path.basename(test[0])
232 if name_counts[name] > 1:
233 if '/' in test[1]:
234 name += '_' + os.path.splitext(os.path.basename(test[1]))[0]
235 else:
236 name += '_' + test[1].replace('-', '_')
237
238 if not first:
239 out.write('\n')
240 first = False
241
242 src_prefix = 'src/' + test[0]
243 for src in files['test']:
244 if src.startswith(src_prefix):
245 src = src
246 break
247 else:
248 raise ValueError("Can't find source for %s" % test[0])
249
Chuck Haysc608d6b2015-10-06 17:54:16 -0700250 out.write(' native.cc_test(\n')
251 out.write(' name = "%s",\n' % name)
252 out.write(' size = "small",\n')
253 out.write(' srcs = ["%s"] + test_support_sources_complete,\n' % src)
Adam Langley9c164b22015-06-10 18:54:47 -0700254
255 data_files = []
256 if len(test) > 1:
257
Chuck Haysc608d6b2015-10-06 17:54:16 -0700258 out.write(' args = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700259 for arg in test[1:]:
260 if '/' in arg:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700261 out.write(' "$(location src/%s)",\n' % arg)
Adam Langley9c164b22015-06-10 18:54:47 -0700262 data_files.append('src/%s' % arg)
263 else:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700264 out.write(' "%s",\n' % arg)
265 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700266
Chuck Haysc608d6b2015-10-06 17:54:16 -0700267 out.write(' copts = copts,\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700268
269 if len(data_files) > 0:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700270 out.write(' data = [\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700271 for filename in data_files:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700272 out.write(' "%s",\n' % filename)
273 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700274
275 if 'ssl/' in test[0]:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700276 out.write(' deps = [\n')
277 out.write(' ":crypto",\n')
278 out.write(' ":ssl",\n')
279 out.write(' ],\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700280 else:
Chuck Haysc608d6b2015-10-06 17:54:16 -0700281 out.write(' deps = [":crypto"],\n')
282 out.write(' )\n')
Adam Langley9c164b22015-06-10 18:54:47 -0700283
Adam Langley049ef412015-06-09 18:20:57 -0700284
Adam Langley9e1a6602015-05-05 17:47:53 -0700285def FindCMakeFiles(directory):
286 """Returns list of all CMakeLists.txt files recursively in directory."""
287 cmakefiles = []
288
289 for (path, _, filenames) in os.walk(directory):
290 for filename in filenames:
291 if filename == 'CMakeLists.txt':
292 cmakefiles.append(os.path.join(path, filename))
293
294 return cmakefiles
295
296
297def NoTests(dent, is_dir):
298 """Filter function that can be passed to FindCFiles in order to remove test
299 sources."""
300 if is_dir:
301 return dent != 'test'
302 return 'test.' not in dent and not dent.startswith('example_')
303
304
305def OnlyTests(dent, is_dir):
306 """Filter function that can be passed to FindCFiles in order to remove
307 non-test sources."""
308 if is_dir:
David Benjamin26073832015-05-11 20:52:48 -0400309 return dent != 'test'
Adam Langley9e1a6602015-05-05 17:47:53 -0700310 return '_test.' in dent or dent.startswith('example_')
311
312
David Benjamin26073832015-05-11 20:52:48 -0400313def AllFiles(dent, is_dir):
314 """Filter function that can be passed to FindCFiles in order to include all
315 sources."""
316 return True
317
318
Adam Langley049ef412015-06-09 18:20:57 -0700319def SSLHeaderFiles(dent, is_dir):
320 return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h']
321
322
Adam Langley9e1a6602015-05-05 17:47:53 -0700323def FindCFiles(directory, filter_func):
324 """Recurses through directory and returns a list of paths to all the C source
325 files that pass filter_func."""
326 cfiles = []
327
328 for (path, dirnames, filenames) in os.walk(directory):
329 for filename in filenames:
330 if not filename.endswith('.c') and not filename.endswith('.cc'):
331 continue
332 if not filter_func(filename, False):
333 continue
334 cfiles.append(os.path.join(path, filename))
335
336 for (i, dirname) in enumerate(dirnames):
337 if not filter_func(dirname, True):
338 del dirnames[i]
339
340 return cfiles
341
342
Adam Langley049ef412015-06-09 18:20:57 -0700343def FindHeaderFiles(directory, filter_func):
344 """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
345 hfiles = []
346
347 for (path, dirnames, filenames) in os.walk(directory):
348 for filename in filenames:
349 if not filename.endswith('.h'):
350 continue
351 if not filter_func(filename, False):
352 continue
353 hfiles.append(os.path.join(path, filename))
354
355 return hfiles
356
357
Adam Langley9e1a6602015-05-05 17:47:53 -0700358def ExtractPerlAsmFromCMakeFile(cmakefile):
359 """Parses the contents of the CMakeLists.txt file passed as an argument and
360 returns a list of all the perlasm() directives found in the file."""
361 perlasms = []
362 with open(cmakefile) as f:
363 for line in f:
364 line = line.strip()
365 if not line.startswith('perlasm('):
366 continue
367 if not line.endswith(')'):
368 raise ValueError('Bad perlasm line in %s' % cmakefile)
369 # Remove "perlasm(" from start and ")" from end
370 params = line[8:-1].split()
371 if len(params) < 2:
372 raise ValueError('Bad perlasm line in %s' % cmakefile)
373 perlasms.append({
374 'extra_args': params[2:],
375 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
376 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
377 })
378
379 return perlasms
380
381
382def ReadPerlAsmOperations():
383 """Returns a list of all perlasm() directives found in CMake config files in
384 src/."""
385 perlasms = []
386 cmakefiles = FindCMakeFiles('src')
387
388 for cmakefile in cmakefiles:
389 perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
390
391 return perlasms
392
393
394def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
395 """Runs the a perlasm script and puts the output into output_filename."""
396 base_dir = os.path.dirname(output_filename)
397 if not os.path.isdir(base_dir):
398 os.makedirs(base_dir)
399 output = subprocess.check_output(
400 ['perl', input_filename, perlasm_style] + extra_args)
401 with open(output_filename, 'w+') as out_file:
402 out_file.write(output)
403
404
405def ArchForAsmFilename(filename):
406 """Returns the architectures that a given asm file should be compiled for
407 based on substrings in the filename."""
408
409 if 'x86_64' in filename or 'avx2' in filename:
410 return ['x86_64']
411 elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
412 return ['x86']
413 elif 'armx' in filename:
414 return ['arm', 'aarch64']
415 elif 'armv8' in filename:
416 return ['aarch64']
417 elif 'arm' in filename:
418 return ['arm']
419 else:
420 raise ValueError('Unknown arch for asm filename: ' + filename)
421
422
423def WriteAsmFiles(perlasms):
424 """Generates asm files from perlasm directives for each supported OS x
425 platform combination."""
426 asmfiles = {}
427
428 for osarch in OS_ARCH_COMBOS:
429 (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
430 key = (osname, arch)
431 outDir = '%s-%s' % key
432
433 for perlasm in perlasms:
434 filename = os.path.basename(perlasm['input'])
435 output = perlasm['output']
436 if not output.startswith('src'):
437 raise ValueError('output missing src: %s' % output)
438 output = os.path.join(outDir, output[4:])
William Hessec618c402015-06-22 16:34:02 +0200439 if output.endswith('-armx.${ASM_EXT}'):
440 output = output.replace('-armx',
441 '-armx64' if arch == 'aarch64' else '-armx32')
Adam Langley9e1a6602015-05-05 17:47:53 -0700442 output = output.replace('${ASM_EXT}', asm_ext)
443
444 if arch in ArchForAsmFilename(filename):
445 PerlAsm(output, perlasm['input'], perlasm_style,
446 perlasm['extra_args'] + extra_args)
447 asmfiles.setdefault(key, []).append(output)
448
449 for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
450 asmfiles.setdefault(key, []).extend(non_perl_asm_files)
451
452 return asmfiles
453
454
Adam Langley049ef412015-06-09 18:20:57 -0700455def main(platforms):
Adam Langley9e1a6602015-05-05 17:47:53 -0700456 crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
457 ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
458 tool_cc_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
459
460 # Generate err_data.c
461 with open('err_data.c', 'w+') as err_data:
462 subprocess.check_call(['go', 'run', 'err_data_generate.go'],
463 cwd=os.path.join('src', 'crypto', 'err'),
464 stdout=err_data)
465 crypto_c_files.append('err_data.c')
466
David Benjamin26073832015-05-11 20:52:48 -0400467 test_support_cc_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
468 AllFiles)
469
Adam Langley9e1a6602015-05-05 17:47:53 -0700470 test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
471 test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
472
Adam Langley049ef412015-06-09 18:20:57 -0700473 ssl_h_files = (
474 FindHeaderFiles(
475 os.path.join('src', 'include', 'openssl'),
476 SSLHeaderFiles))
477
478 def NotSSLHeaderFiles(filename, is_dir):
479 return not SSLHeaderFiles(filename, is_dir)
480 crypto_h_files = (
481 FindHeaderFiles(
482 os.path.join('src', 'include', 'openssl'),
483 NotSSLHeaderFiles))
484
485 ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
486 crypto_internal_h_files = FindHeaderFiles(
487 os.path.join('src', 'crypto'), NoTests)
488
Adam Langley9c164b22015-06-10 18:54:47 -0700489 with open('src/util/all_tests.json', 'r') as f:
490 tests = json.load(f)
491 test_binaries = set([test[0] for test in tests])
492 test_sources = set([
493 test.replace('.cc', '').replace('.c', '').replace(
494 'src/',
495 '')
496 for test in test_c_files])
497 if test_binaries != test_sources:
498 print 'Test sources and configured tests do not match'
499 a = test_binaries.difference(test_sources)
500 if len(a) > 0:
501 print 'These tests are configured without sources: ' + str(a)
502 b = test_sources.difference(test_binaries)
503 if len(b) > 0:
504 print 'These test sources are not configured: ' + str(b)
505
Adam Langley9e1a6602015-05-05 17:47:53 -0700506 files = {
507 'crypto': crypto_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700508 'crypto_headers': crypto_h_files,
509 'crypto_internal_headers': crypto_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700510 'ssl': ssl_c_files,
Adam Langley049ef412015-06-09 18:20:57 -0700511 'ssl_headers': ssl_h_files,
512 'ssl_internal_headers': ssl_internal_h_files,
Adam Langley9e1a6602015-05-05 17:47:53 -0700513 'tool': tool_cc_files,
514 'test': test_c_files,
David Benjamin26073832015-05-11 20:52:48 -0400515 'test_support': test_support_cc_files,
Adam Langley9c164b22015-06-10 18:54:47 -0700516 'tests': tests,
Adam Langley9e1a6602015-05-05 17:47:53 -0700517 }
518
519 asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
520
Adam Langley049ef412015-06-09 18:20:57 -0700521 for platform in platforms:
522 platform.WriteFiles(files, asm_outputs)
Adam Langley9e1a6602015-05-05 17:47:53 -0700523
524 return 0
525
526
527def Usage():
Adam Langley049ef412015-06-09 18:20:57 -0700528 print 'Usage: python %s [chromium|android|android-standalone|bazel]' % sys.argv[0]
Adam Langley9e1a6602015-05-05 17:47:53 -0700529 sys.exit(1)
530
531
532if __name__ == '__main__':
Adam Langley049ef412015-06-09 18:20:57 -0700533 if len(sys.argv) < 2:
Adam Langley9e1a6602015-05-05 17:47:53 -0700534 Usage()
535
Adam Langley049ef412015-06-09 18:20:57 -0700536 platforms = []
537 for s in sys.argv[1:]:
538 if s == 'chromium' or s == 'gyp':
539 platforms.append(Chromium())
540 elif s == 'android':
541 platforms.append(Android())
542 elif s == 'android-standalone':
543 platforms.append(AndroidStandalone())
544 elif s == 'bazel':
545 platforms.append(Bazel())
546 else:
547 Usage()
Adam Langley9e1a6602015-05-05 17:47:53 -0700548
Adam Langley049ef412015-06-09 18:20:57 -0700549 sys.exit(main(platforms))