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.
 
 
 
 
 
 

342 line
11 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. # OS_ARCH_COMBOS maps from OS and platform to the OpenSSL assembly "style" for
  21. # that platform and the extension used by asm files.
  22. OS_ARCH_COMBOS = [
  23. ('linux', 'arm', 'linux32', [], 'S'),
  24. ('linux', 'aarch64', 'linux64', [], 'S'),
  25. ('linux', 'x86', 'elf', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
  26. ('linux', 'x86_64', 'elf', [], 'S'),
  27. ('mac', 'x86', 'macosx', ['-fPIC', '-DOPENSSL_IA32_SSE2'], 'S'),
  28. ('mac', 'x86_64', 'macosx', [], 'S'),
  29. ('win', 'x86', 'win32n', ['-DOPENSSL_IA32_SSE2'], 'asm'),
  30. ('win', 'x86_64', 'nasm', [], 'asm'),
  31. ]
  32. # NON_PERL_FILES enumerates assembly files that are not processed by the
  33. # perlasm system.
  34. NON_PERL_FILES = {
  35. ('linux', 'arm'): [
  36. 'src/crypto/poly1305/poly1305_arm_asm.S',
  37. 'src/crypto/chacha/chacha_vec_arm.S',
  38. 'src/crypto/cpu-arm-asm.S',
  39. ],
  40. }
  41. class Chromium(object):
  42. def __init__(self):
  43. self.header = \
  44. """# Copyright (c) 2014 The Chromium Authors. All rights reserved.
  45. # Use of this source code is governed by a BSD-style license that can be
  46. # found in the LICENSE file.
  47. # This file is created by generate_build_files.py. Do not edit manually.
  48. """
  49. def PrintVariableSection(self, out, name, files):
  50. out.write(' \'%s\': [\n' % name)
  51. for f in sorted(files):
  52. out.write(' \'%s\',\n' % f)
  53. out.write(' ],\n')
  54. def WriteFiles(self, files, asm_outputs):
  55. with open('boringssl.gypi', 'w+') as gypi:
  56. gypi.write(self.header + '{\n \'variables\': {\n')
  57. self.PrintVariableSection(
  58. gypi, 'boringssl_lib_sources', files['crypto'] + files['ssl'])
  59. for ((osname, arch), asm_files) in asm_outputs:
  60. self.PrintVariableSection(gypi, 'boringssl_%s_%s_sources' %
  61. (osname, arch), asm_files)
  62. gypi.write(' }\n}\n')
  63. with open('boringssl_tests.gypi', 'w+') as test_gypi:
  64. test_gypi.write(self.header + '{\n \'targets\': [\n')
  65. test_names = []
  66. for test in sorted(files['test']):
  67. test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
  68. test_gypi.write(""" {
  69. 'target_name': '%s',
  70. 'type': 'executable',
  71. 'dependencies': [
  72. 'boringssl.gyp:boringssl',
  73. ],
  74. 'sources': [
  75. '%s',
  76. ],
  77. # TODO(davidben): Fix size_t truncations in BoringSSL.
  78. # https://crbug.com/429039
  79. 'msvs_disabled_warnings': [ 4267, ],
  80. },\n""" % (test_name, test))
  81. test_names.append(test_name)
  82. test_names.sort()
  83. test_gypi.write(""" ],
  84. 'variables': {
  85. 'boringssl_test_targets': [\n""")
  86. for test in test_names:
  87. test_gypi.write(""" '%s',\n""" % test)
  88. test_gypi.write(' ],\n }\n}\n')
  89. class Android(object):
  90. def __init__(self):
  91. self.header = \
  92. """# Copyright (C) 2015 The Android Open Source Project
  93. #
  94. # Licensed under the Apache License, Version 2.0 (the "License");
  95. # you may not use this file except in compliance with the License.
  96. # You may obtain a copy of the License at
  97. #
  98. # http://www.apache.org/licenses/LICENSE-2.0
  99. #
  100. # Unless required by applicable law or agreed to in writing, software
  101. # distributed under the License is distributed on an "AS IS" BASIS,
  102. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  103. # See the License for the specific language governing permissions and
  104. # limitations under the License.
  105. """
  106. def PrintVariableSection(self, out, name, files):
  107. out.write('%s := \\\n' % name)
  108. for f in sorted(files):
  109. out.write(' %s\\\n' % f)
  110. out.write('\n')
  111. def WriteFiles(self, files, asm_outputs):
  112. with open('sources.mk', 'w+') as makefile:
  113. makefile.write(self.header)
  114. files['crypto'].append('android_compat_hacks.c')
  115. files['crypto'].append('android_compat_keywrap.c')
  116. self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
  117. self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
  118. self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
  119. for ((osname, arch), asm_files) in asm_outputs:
  120. self.PrintVariableSection(
  121. makefile, '%s_%s_sources' % (osname, arch), asm_files)
  122. def FindCMakeFiles(directory):
  123. """Returns list of all CMakeLists.txt files recursively in directory."""
  124. cmakefiles = []
  125. for (path, _, filenames) in os.walk(directory):
  126. for filename in filenames:
  127. if filename == 'CMakeLists.txt':
  128. cmakefiles.append(os.path.join(path, filename))
  129. return cmakefiles
  130. def NoTests(dent, is_dir):
  131. """Filter function that can be passed to FindCFiles in order to remove test
  132. sources."""
  133. if is_dir:
  134. return dent != 'test'
  135. return 'test.' not in dent and not dent.startswith('example_')
  136. def OnlyTests(dent, is_dir):
  137. """Filter function that can be passed to FindCFiles in order to remove
  138. non-test sources."""
  139. if is_dir:
  140. return True
  141. return '_test.' in dent or dent.startswith('example_')
  142. def FindCFiles(directory, filter_func):
  143. """Recurses through directory and returns a list of paths to all the C source
  144. files that pass filter_func."""
  145. cfiles = []
  146. for (path, dirnames, filenames) in os.walk(directory):
  147. for filename in filenames:
  148. if not filename.endswith('.c') and not filename.endswith('.cc'):
  149. continue
  150. if not filter_func(filename, False):
  151. continue
  152. cfiles.append(os.path.join(path, filename))
  153. for (i, dirname) in enumerate(dirnames):
  154. if not filter_func(dirname, True):
  155. del dirnames[i]
  156. return cfiles
  157. def ExtractPerlAsmFromCMakeFile(cmakefile):
  158. """Parses the contents of the CMakeLists.txt file passed as an argument and
  159. returns a list of all the perlasm() directives found in the file."""
  160. perlasms = []
  161. with open(cmakefile) as f:
  162. for line in f:
  163. line = line.strip()
  164. if not line.startswith('perlasm('):
  165. continue
  166. if not line.endswith(')'):
  167. raise ValueError('Bad perlasm line in %s' % cmakefile)
  168. # Remove "perlasm(" from start and ")" from end
  169. params = line[8:-1].split()
  170. if len(params) < 2:
  171. raise ValueError('Bad perlasm line in %s' % cmakefile)
  172. perlasms.append({
  173. 'extra_args': params[2:],
  174. 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
  175. 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
  176. })
  177. return perlasms
  178. def ReadPerlAsmOperations():
  179. """Returns a list of all perlasm() directives found in CMake config files in
  180. src/."""
  181. perlasms = []
  182. cmakefiles = FindCMakeFiles('src')
  183. for cmakefile in cmakefiles:
  184. perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
  185. return perlasms
  186. def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
  187. """Runs the a perlasm script and puts the output into output_filename."""
  188. base_dir = os.path.dirname(output_filename)
  189. if not os.path.isdir(base_dir):
  190. os.makedirs(base_dir)
  191. output = subprocess.check_output(
  192. ['perl', input_filename, perlasm_style] + extra_args)
  193. with open(output_filename, 'w+') as out_file:
  194. out_file.write(output)
  195. def ArchForAsmFilename(filename):
  196. """Returns the architectures that a given asm file should be compiled for
  197. based on substrings in the filename."""
  198. if 'x86_64' in filename or 'avx2' in filename:
  199. return ['x86_64']
  200. elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
  201. return ['x86']
  202. elif 'armx' in filename:
  203. return ['arm', 'aarch64']
  204. elif 'armv8' in filename:
  205. return ['aarch64']
  206. elif 'arm' in filename:
  207. return ['arm']
  208. else:
  209. raise ValueError('Unknown arch for asm filename: ' + filename)
  210. def WriteAsmFiles(perlasms):
  211. """Generates asm files from perlasm directives for each supported OS x
  212. platform combination."""
  213. asmfiles = {}
  214. for osarch in OS_ARCH_COMBOS:
  215. (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
  216. key = (osname, arch)
  217. outDir = '%s-%s' % key
  218. for perlasm in perlasms:
  219. filename = os.path.basename(perlasm['input'])
  220. output = perlasm['output']
  221. if not output.startswith('src'):
  222. raise ValueError('output missing src: %s' % output)
  223. output = os.path.join(outDir, output[4:])
  224. output = output.replace('${ASM_EXT}', asm_ext)
  225. if arch in ArchForAsmFilename(filename):
  226. PerlAsm(output, perlasm['input'], perlasm_style,
  227. perlasm['extra_args'] + extra_args)
  228. asmfiles.setdefault(key, []).append(output)
  229. for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
  230. asmfiles.setdefault(key, []).extend(non_perl_asm_files)
  231. return asmfiles
  232. def main(platform):
  233. crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
  234. ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
  235. tool_cc_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
  236. # Generate err_data.c
  237. with open('err_data.c', 'w+') as err_data:
  238. subprocess.check_call(['go', 'run', 'err_data_generate.go'],
  239. cwd=os.path.join('src', 'crypto', 'err'),
  240. stdout=err_data)
  241. crypto_c_files.append('err_data.c')
  242. test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
  243. test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
  244. files = {
  245. 'crypto': crypto_c_files,
  246. 'ssl': ssl_c_files,
  247. 'tool': tool_cc_files,
  248. 'test': test_c_files,
  249. }
  250. asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
  251. platform.WriteFiles(files, asm_outputs)
  252. return 0
  253. def Usage():
  254. print 'Usage: python %s [chromium|android]' % sys.argv[0]
  255. sys.exit(1)
  256. if __name__ == '__main__':
  257. if len(sys.argv) != 2:
  258. Usage()
  259. platform = None
  260. if sys.argv[1] == 'chromium':
  261. platform = Chromium()
  262. elif sys.argv[1] == 'android':
  263. platform = Android()
  264. else:
  265. Usage()
  266. sys.exit(main(platform))