You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

634 line
20 KiB

  1. # 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. """Enumerates the BoringSSL source in src/ and either generates two gypi files
  15. (boringssl.gypi and boringssl_tests.gypi) for Chromium, or generates
  16. source-list files for Android."""
  17. import os
  18. import subprocess
  19. import sys
  20. import json
  21. # OS_ARCH_COMBOS maps from OS and platform to the OpenSSL assembly "style" for
  22. # that platform and the extension used by asm files.
  23. OS_ARCH_COMBOS = [
  24. ('linux', 'arm', 'linux32', [], 'S'),
  25. ('linux', 'aarch64', 'linux64', [], 'S'),
  26. ('linux', 'x86', 'elf', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
  27. ('linux', 'x86_64', 'elf', [], 'S'),
  28. ('mac', 'x86', 'macosx', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
  29. ('mac', 'x86_64', 'macosx', [], 'S'),
  30. ('win', 'x86', 'win32n', ['-DOPENSSL_IA32_SSE2'], 'asm'),
  31. ('win', 'x86_64', 'nasm', [], 'asm'),
  32. ]
  33. # NON_PERL_FILES enumerates assembly files that are not processed by the
  34. # perlasm system.
  35. NON_PERL_FILES = {
  36. ('linux', 'arm'): [
  37. 'src/crypto/curve25519/asm/x25519-asm-arm.S',
  38. 'src/crypto/poly1305/poly1305_arm_asm.S',
  39. ],
  40. ('linux', 'x86_64'): [
  41. 'src/crypto/curve25519/asm/x25519-asm-x86_64.S',
  42. ],
  43. }
  44. class Android(object):
  45. def __init__(self):
  46. self.header = \
  47. """# Copyright (C) 2015 The Android Open Source Project
  48. #
  49. # Licensed under the Apache License, Version 2.0 (the "License");
  50. # you may not use this file except in compliance with the License.
  51. # You may obtain a copy of the License at
  52. #
  53. # http://www.apache.org/licenses/LICENSE-2.0
  54. #
  55. # Unless required by applicable law or agreed to in writing, software
  56. # distributed under the License is distributed on an "AS IS" BASIS,
  57. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  58. # See the License for the specific language governing permissions and
  59. # limitations under the License.
  60. """
  61. def ExtraFiles(self):
  62. return ['android_compat_hacks.c', 'android_compat_keywrap.c']
  63. def PrintVariableSection(self, out, name, files):
  64. out.write('%s := \\\n' % name)
  65. for f in sorted(files):
  66. out.write(' %s\\\n' % f)
  67. out.write('\n')
  68. def WriteFiles(self, files, asm_outputs):
  69. with open('sources.mk', 'w+') as makefile:
  70. makefile.write(self.header)
  71. crypto_files = files['crypto'] + self.ExtraFiles()
  72. self.PrintVariableSection(makefile, 'crypto_sources', crypto_files)
  73. self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
  74. self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
  75. for ((osname, arch), asm_files) in asm_outputs:
  76. self.PrintVariableSection(
  77. makefile, '%s_%s_sources' % (osname, arch), asm_files)
  78. class AndroidStandalone(Android):
  79. """AndroidStandalone is for Android builds outside of the Android-system, i.e.
  80. for applications that wish wish to ship BoringSSL.
  81. """
  82. def ExtraFiles(self):
  83. return []
  84. class Bazel(object):
  85. """Bazel outputs files suitable for including in Bazel files."""
  86. def __init__(self):
  87. self.firstSection = True
  88. self.header = \
  89. """# This file is created by generate_build_files.py. Do not edit manually.
  90. """
  91. def PrintVariableSection(self, out, name, files):
  92. if not self.firstSection:
  93. out.write('\n')
  94. self.firstSection = False
  95. out.write('%s = [\n' % name)
  96. for f in sorted(files):
  97. out.write(' "%s",\n' % f)
  98. out.write(']\n')
  99. def WriteFiles(self, files, asm_outputs):
  100. with open('BUILD.generated.bzl', 'w+') as out:
  101. out.write(self.header)
  102. self.PrintVariableSection(out, 'ssl_headers', files['ssl_headers'])
  103. self.PrintVariableSection(
  104. out, 'ssl_internal_headers', files['ssl_internal_headers'])
  105. self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
  106. self.PrintVariableSection(out, 'crypto_headers', files['crypto_headers'])
  107. self.PrintVariableSection(
  108. out, 'crypto_internal_headers', files['crypto_internal_headers'])
  109. self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
  110. self.PrintVariableSection(out, 'tool_sources', files['tool'])
  111. for ((osname, arch), asm_files) in asm_outputs:
  112. self.PrintVariableSection(
  113. out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
  114. with open('BUILD.generated_tests.bzl', 'w+') as out:
  115. out.write(self.header)
  116. out.write('test_support_sources = [\n')
  117. for filename in files['test_support']:
  118. if os.path.basename(filename) == 'malloc.cc':
  119. continue
  120. out.write(' "%s",\n' % filename)
  121. out.write(']\n\n')
  122. out.write('def create_tests(copts):\n')
  123. out.write(' test_support_sources_complete = test_support_sources + \\\n')
  124. out.write(' native.glob(["src/crypto/test/*.h"])\n')
  125. name_counts = {}
  126. for test in files['tests']:
  127. name = os.path.basename(test[0])
  128. name_counts[name] = name_counts.get(name, 0) + 1
  129. first = True
  130. for test in files['tests']:
  131. name = os.path.basename(test[0])
  132. if name_counts[name] > 1:
  133. if '/' in test[1]:
  134. name += '_' + os.path.splitext(os.path.basename(test[1]))[0]
  135. else:
  136. name += '_' + test[1].replace('-', '_')
  137. if not first:
  138. out.write('\n')
  139. first = False
  140. src_prefix = 'src/' + test[0]
  141. for src in files['test']:
  142. if src.startswith(src_prefix):
  143. src = src
  144. break
  145. else:
  146. raise ValueError("Can't find source for %s" % test[0])
  147. out.write(' native.cc_test(\n')
  148. out.write(' name = "%s",\n' % name)
  149. out.write(' size = "small",\n')
  150. out.write(' srcs = ["%s"] + test_support_sources_complete,\n' % src)
  151. data_files = []
  152. if len(test) > 1:
  153. out.write(' args = [\n')
  154. for arg in test[1:]:
  155. if '/' in arg:
  156. out.write(' "$(location src/%s)",\n' % arg)
  157. data_files.append('src/%s' % arg)
  158. else:
  159. out.write(' "%s",\n' % arg)
  160. out.write(' ],\n')
  161. out.write(' copts = copts,\n')
  162. if len(data_files) > 0:
  163. out.write(' data = [\n')
  164. for filename in data_files:
  165. out.write(' "%s",\n' % filename)
  166. out.write(' ],\n')
  167. if 'ssl/' in test[0]:
  168. out.write(' deps = [\n')
  169. out.write(' ":crypto",\n')
  170. out.write(' ":ssl",\n')
  171. out.write(' ],\n')
  172. else:
  173. out.write(' deps = [":crypto"],\n')
  174. out.write(' )\n')
  175. class GN(object):
  176. def __init__(self):
  177. self.firstSection = True
  178. self.header = \
  179. """# Copyright (c) 2016 The Chromium Authors. All rights reserved.
  180. # Use of this source code is governed by a BSD-style license that can be
  181. # found in the LICENSE file.
  182. # This file is created by generate_build_files.py. Do not edit manually.
  183. """
  184. def PrintVariableSection(self, out, name, files):
  185. if not self.firstSection:
  186. out.write('\n')
  187. self.firstSection = False
  188. out.write('%s = [\n' % name)
  189. for f in sorted(files):
  190. out.write(' "%s",\n' % f)
  191. out.write(']\n')
  192. def WriteFiles(self, files, asm_outputs):
  193. with open('BUILD.generated.gni', 'w+') as out:
  194. out.write(self.header)
  195. self.PrintVariableSection(out, 'crypto_sources', files['crypto'])
  196. self.PrintVariableSection(out, 'ssl_sources', files['ssl'])
  197. for ((osname, arch), asm_files) in asm_outputs:
  198. self.PrintVariableSection(
  199. out, 'crypto_sources_%s_%s' % (osname, arch), asm_files)
  200. fuzzers = [os.path.splitext(os.path.basename(fuzzer))[0]
  201. for fuzzer in files['fuzz']]
  202. self.PrintVariableSection(out, 'fuzzers', fuzzers)
  203. with open('BUILD.generated_tests.gni', 'w+') as out:
  204. self.firstSection = True
  205. out.write(self.header)
  206. self.PrintVariableSection(out, '_test_support_sources',
  207. files['test_support'])
  208. out.write('\n')
  209. out.write('template("create_tests") {\n')
  210. all_tests = []
  211. for test in sorted(files['test']):
  212. test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
  213. all_tests.append(test_name)
  214. out.write(' executable("%s") {\n' % test_name)
  215. out.write(' sources = [\n')
  216. out.write(' "%s",\n' % test)
  217. out.write(' ]\n')
  218. out.write(' sources += _test_support_sources\n')
  219. out.write(' if (defined(invoker.configs_exclude)) {\n')
  220. out.write(' configs -= invoker.configs_exclude\n')
  221. out.write(' }\n')
  222. out.write(' configs += invoker.configs\n')
  223. out.write(' deps = invoker.deps\n')
  224. out.write(' }\n')
  225. out.write('\n')
  226. out.write(' group(target_name) {\n')
  227. out.write(' deps = [\n')
  228. for test_name in sorted(all_tests):
  229. out.write(' ":%s",\n' % test_name)
  230. out.write(' ]\n')
  231. out.write(' }\n')
  232. out.write('}\n')
  233. class GYP(object):
  234. def __init__(self):
  235. self.header = \
  236. """# Copyright (c) 2016 The Chromium Authors. All rights reserved.
  237. # Use of this source code is governed by a BSD-style license that can be
  238. # found in the LICENSE file.
  239. # This file is created by generate_build_files.py. Do not edit manually.
  240. """
  241. def PrintVariableSection(self, out, name, files):
  242. out.write(' \'%s\': [\n' % name)
  243. for f in sorted(files):
  244. out.write(' \'%s\',\n' % f)
  245. out.write(' ],\n')
  246. def WriteFiles(self, files, asm_outputs):
  247. with open('boringssl.gypi', 'w+') as gypi:
  248. gypi.write(self.header + '{\n \'variables\': {\n')
  249. self.PrintVariableSection(
  250. gypi, 'boringssl_ssl_sources', files['ssl'])
  251. self.PrintVariableSection(
  252. gypi, 'boringssl_crypto_sources', files['crypto'])
  253. for ((osname, arch), asm_files) in asm_outputs:
  254. self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
  255. (osname, arch), asm_files)
  256. gypi.write(' }\n}\n')
  257. with open('boringssl_tests.gypi', 'w+') as test_gypi:
  258. test_gypi.write(self.header + '{\n \'targets\': [\n')
  259. test_names = []
  260. for test in sorted(files['test']):
  261. test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
  262. test_gypi.write(""" {
  263. 'target_name': '%s',
  264. 'type': 'executable',
  265. 'dependencies': [
  266. 'boringssl.gyp:boringssl',
  267. ],
  268. 'sources': [
  269. '%s',
  270. '<@(boringssl_test_support_sources)',
  271. ],
  272. # TODO(davidben): Fix size_t truncations in BoringSSL.
  273. # https://crbug.com/429039
  274. 'msvs_disabled_warnings': [ 4267, ],
  275. },\n""" % (test_name, test))
  276. test_names.append(test_name)
  277. test_names.sort()
  278. test_gypi.write(' ],\n \'variables\': {\n')
  279. self.PrintVariableSection(
  280. test_gypi, 'boringssl_test_support_sources', files['test_support'])
  281. test_gypi.write(' \'boringssl_test_targets\': [\n')
  282. for test in sorted(test_names):
  283. test_gypi.write(""" '%s',\n""" % test)
  284. test_gypi.write(' ],\n }\n}\n')
  285. def FindCMakeFiles(directory):
  286. """Returns list of all CMakeLists.txt files recursively in directory."""
  287. cmakefiles = []
  288. for (path, _, filenames) in os.walk(directory):
  289. for filename in filenames:
  290. if filename == 'CMakeLists.txt':
  291. cmakefiles.append(os.path.join(path, filename))
  292. return cmakefiles
  293. def NoTests(dent, is_dir):
  294. """Filter function that can be passed to FindCFiles in order to remove test
  295. sources."""
  296. if is_dir:
  297. return dent != 'test'
  298. return 'test.' not in dent and not dent.startswith('example_')
  299. def OnlyTests(dent, is_dir):
  300. """Filter function that can be passed to FindCFiles in order to remove
  301. non-test sources."""
  302. if is_dir:
  303. return dent != 'test'
  304. return '_test.' in dent or dent.startswith('example_')
  305. def AllFiles(dent, is_dir):
  306. """Filter function that can be passed to FindCFiles in order to include all
  307. sources."""
  308. return True
  309. def SSLHeaderFiles(dent, is_dir):
  310. return dent in ['ssl.h', 'tls1.h', 'ssl23.h', 'ssl3.h', 'dtls1.h']
  311. def FindCFiles(directory, filter_func):
  312. """Recurses through directory and returns a list of paths to all the C source
  313. files that pass filter_func."""
  314. cfiles = []
  315. for (path, dirnames, filenames) in os.walk(directory):
  316. for filename in filenames:
  317. if not filename.endswith('.c') and not filename.endswith('.cc'):
  318. continue
  319. if not filter_func(filename, False):
  320. continue
  321. cfiles.append(os.path.join(path, filename))
  322. for (i, dirname) in enumerate(dirnames):
  323. if not filter_func(dirname, True):
  324. del dirnames[i]
  325. return cfiles
  326. def FindHeaderFiles(directory, filter_func):
  327. """Recurses through directory and returns a list of paths to all the header files that pass filter_func."""
  328. hfiles = []
  329. for (path, dirnames, filenames) in os.walk(directory):
  330. for filename in filenames:
  331. if not filename.endswith('.h'):
  332. continue
  333. if not filter_func(filename, False):
  334. continue
  335. hfiles.append(os.path.join(path, filename))
  336. return hfiles
  337. def ExtractPerlAsmFromCMakeFile(cmakefile):
  338. """Parses the contents of the CMakeLists.txt file passed as an argument and
  339. returns a list of all the perlasm() directives found in the file."""
  340. perlasms = []
  341. with open(cmakefile) as f:
  342. for line in f:
  343. line = line.strip()
  344. if not line.startswith('perlasm('):
  345. continue
  346. if not line.endswith(')'):
  347. raise ValueError('Bad perlasm line in %s' % cmakefile)
  348. # Remove "perlasm(" from start and ")" from end
  349. params = line[8:-1].split()
  350. if len(params) < 2:
  351. raise ValueError('Bad perlasm line in %s' % cmakefile)
  352. perlasms.append({
  353. 'extra_args': params[2:],
  354. 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
  355. 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
  356. })
  357. return perlasms
  358. def ReadPerlAsmOperations():
  359. """Returns a list of all perlasm() directives found in CMake config files in
  360. src/."""
  361. perlasms = []
  362. cmakefiles = FindCMakeFiles('src')
  363. for cmakefile in cmakefiles:
  364. perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
  365. return perlasms
  366. def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
  367. """Runs the a perlasm script and puts the output into output_filename."""
  368. base_dir = os.path.dirname(output_filename)
  369. if not os.path.isdir(base_dir):
  370. os.makedirs(base_dir)
  371. output = subprocess.check_output(
  372. ['perl', input_filename, perlasm_style] + extra_args)
  373. with open(output_filename, 'w+') as out_file:
  374. out_file.write(output)
  375. def ArchForAsmFilename(filename):
  376. """Returns the architectures that a given asm file should be compiled for
  377. based on substrings in the filename."""
  378. if 'x86_64' in filename or 'avx2' in filename:
  379. return ['x86_64']
  380. elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
  381. return ['x86']
  382. elif 'armx' in filename:
  383. return ['arm', 'aarch64']
  384. elif 'armv8' in filename:
  385. return ['aarch64']
  386. elif 'arm' in filename:
  387. return ['arm']
  388. else:
  389. raise ValueError('Unknown arch for asm filename: ' + filename)
  390. def WriteAsmFiles(perlasms):
  391. """Generates asm files from perlasm directives for each supported OS x
  392. platform combination."""
  393. asmfiles = {}
  394. for osarch in OS_ARCH_COMBOS:
  395. (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
  396. key = (osname, arch)
  397. outDir = '%s-%s' % key
  398. for perlasm in perlasms:
  399. filename = os.path.basename(perlasm['input'])
  400. output = perlasm['output']
  401. if not output.startswith('src'):
  402. raise ValueError('output missing src: %s' % output)
  403. output = os.path.join(outDir, output[4:])
  404. if output.endswith('-armx.${ASM_EXT}'):
  405. output = output.replace('-armx',
  406. '-armx64' if arch == 'aarch64' else '-armx32')
  407. output = output.replace('${ASM_EXT}', asm_ext)
  408. if arch in ArchForAsmFilename(filename):
  409. PerlAsm(output, perlasm['input'], perlasm_style,
  410. perlasm['extra_args'] + extra_args)
  411. asmfiles.setdefault(key, []).append(output)
  412. for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
  413. asmfiles.setdefault(key, []).extend(non_perl_asm_files)
  414. return asmfiles
  415. def main(platforms):
  416. crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
  417. ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
  418. tool_c_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
  419. # Generate err_data.c
  420. with open('err_data.c', 'w+') as err_data:
  421. subprocess.check_call(['go', 'run', 'err_data_generate.go'],
  422. cwd=os.path.join('src', 'crypto', 'err'),
  423. stdout=err_data)
  424. crypto_c_files.append('err_data.c')
  425. test_support_c_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
  426. AllFiles)
  427. test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
  428. test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
  429. fuzz_c_files = FindCFiles(os.path.join('src', 'fuzz'), NoTests)
  430. ssl_h_files = (
  431. FindHeaderFiles(
  432. os.path.join('src', 'include', 'openssl'),
  433. SSLHeaderFiles))
  434. def NotSSLHeaderFiles(filename, is_dir):
  435. return not SSLHeaderFiles(filename, is_dir)
  436. crypto_h_files = (
  437. FindHeaderFiles(
  438. os.path.join('src', 'include', 'openssl'),
  439. NotSSLHeaderFiles))
  440. ssl_internal_h_files = FindHeaderFiles(os.path.join('src', 'ssl'), NoTests)
  441. crypto_internal_h_files = FindHeaderFiles(
  442. os.path.join('src', 'crypto'), NoTests)
  443. with open('src/util/all_tests.json', 'r') as f:
  444. tests = json.load(f)
  445. # Skip tests for libdecrepit. Consumers import that manually.
  446. tests = [test for test in tests if not test[0].startswith("decrepit/")]
  447. test_binaries = set([test[0] for test in tests])
  448. test_sources = set([
  449. test.replace('.cc', '').replace('.c', '').replace(
  450. 'src/',
  451. '')
  452. for test in test_c_files])
  453. if test_binaries != test_sources:
  454. print 'Test sources and configured tests do not match'
  455. a = test_binaries.difference(test_sources)
  456. if len(a) > 0:
  457. print 'These tests are configured without sources: ' + str(a)
  458. b = test_sources.difference(test_binaries)
  459. if len(b) > 0:
  460. print 'These test sources are not configured: ' + str(b)
  461. files = {
  462. 'crypto': crypto_c_files,
  463. 'crypto_headers': crypto_h_files,
  464. 'crypto_internal_headers': crypto_internal_h_files,
  465. 'fuzz': fuzz_c_files,
  466. 'ssl': ssl_c_files,
  467. 'ssl_headers': ssl_h_files,
  468. 'ssl_internal_headers': ssl_internal_h_files,
  469. 'tool': tool_c_files,
  470. 'test': test_c_files,
  471. 'test_support': test_support_c_files,
  472. 'tests': tests,
  473. }
  474. asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
  475. for platform in platforms:
  476. platform.WriteFiles(files, asm_outputs)
  477. return 0
  478. def Usage():
  479. print 'Usage: python %s [android|android-standalone|bazel|gn|gyp]' % sys.argv[0]
  480. sys.exit(1)
  481. if __name__ == '__main__':
  482. if len(sys.argv) < 2:
  483. Usage()
  484. platforms = []
  485. for s in sys.argv[1:]:
  486. if s == 'android':
  487. platforms.append(Android())
  488. elif s == 'android-standalone':
  489. platforms.append(AndroidStandalone())
  490. elif s == 'bazel':
  491. platforms.append(Bazel())
  492. elif s == 'gn':
  493. platforms.append(GN())
  494. elif s == 'gyp':
  495. platforms.append(GYP())
  496. else:
  497. Usage()
  498. sys.exit(main(platforms))