選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

356 行
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. '<@(boringssl_test_support_sources)',
  77. ],
  78. # TODO(davidben): Fix size_t truncations in BoringSSL.
  79. # https://crbug.com/429039
  80. 'msvs_disabled_warnings': [ 4267, ],
  81. },\n""" % (test_name, test))
  82. test_names.append(test_name)
  83. test_names.sort()
  84. test_gypi.write(' ],\n \'variables\': {\n')
  85. self.PrintVariableSection(
  86. test_gypi, 'boringssl_test_support_sources', files['test_support'])
  87. test_gypi.write(' \'boringssl_test_targets\': [\n')
  88. for test in test_names:
  89. test_gypi.write(""" '%s',\n""" % test)
  90. test_gypi.write(' ],\n }\n}\n')
  91. class Android(object):
  92. def __init__(self):
  93. self.header = \
  94. """# Copyright (C) 2015 The Android Open Source Project
  95. #
  96. # Licensed under the Apache License, Version 2.0 (the "License");
  97. # you may not use this file except in compliance with the License.
  98. # You may obtain a copy of the License at
  99. #
  100. # http://www.apache.org/licenses/LICENSE-2.0
  101. #
  102. # Unless required by applicable law or agreed to in writing, software
  103. # distributed under the License is distributed on an "AS IS" BASIS,
  104. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  105. # See the License for the specific language governing permissions and
  106. # limitations under the License.
  107. """
  108. def PrintVariableSection(self, out, name, files):
  109. out.write('%s := \\\n' % name)
  110. for f in sorted(files):
  111. out.write(' %s\\\n' % f)
  112. out.write('\n')
  113. def WriteFiles(self, files, asm_outputs):
  114. with open('sources.mk', 'w+') as makefile:
  115. makefile.write(self.header)
  116. files['crypto'].append('android_compat_hacks.c')
  117. files['crypto'].append('android_compat_keywrap.c')
  118. self.PrintVariableSection(makefile, 'crypto_sources', files['crypto'])
  119. self.PrintVariableSection(makefile, 'ssl_sources', files['ssl'])
  120. self.PrintVariableSection(makefile, 'tool_sources', files['tool'])
  121. for ((osname, arch), asm_files) in asm_outputs:
  122. self.PrintVariableSection(
  123. makefile, '%s_%s_sources' % (osname, arch), asm_files)
  124. def FindCMakeFiles(directory):
  125. """Returns list of all CMakeLists.txt files recursively in directory."""
  126. cmakefiles = []
  127. for (path, _, filenames) in os.walk(directory):
  128. for filename in filenames:
  129. if filename == 'CMakeLists.txt':
  130. cmakefiles.append(os.path.join(path, filename))
  131. return cmakefiles
  132. def NoTests(dent, is_dir):
  133. """Filter function that can be passed to FindCFiles in order to remove test
  134. sources."""
  135. if is_dir:
  136. return dent != 'test'
  137. return 'test.' not in dent and not dent.startswith('example_')
  138. def OnlyTests(dent, is_dir):
  139. """Filter function that can be passed to FindCFiles in order to remove
  140. non-test sources."""
  141. if is_dir:
  142. return dent != 'test'
  143. return '_test.' in dent or dent.startswith('example_')
  144. def AllFiles(dent, is_dir):
  145. """Filter function that can be passed to FindCFiles in order to include all
  146. sources."""
  147. return True
  148. def FindCFiles(directory, filter_func):
  149. """Recurses through directory and returns a list of paths to all the C source
  150. files that pass filter_func."""
  151. cfiles = []
  152. for (path, dirnames, filenames) in os.walk(directory):
  153. for filename in filenames:
  154. if not filename.endswith('.c') and not filename.endswith('.cc'):
  155. continue
  156. if not filter_func(filename, False):
  157. continue
  158. cfiles.append(os.path.join(path, filename))
  159. for (i, dirname) in enumerate(dirnames):
  160. if not filter_func(dirname, True):
  161. del dirnames[i]
  162. return cfiles
  163. def ExtractPerlAsmFromCMakeFile(cmakefile):
  164. """Parses the contents of the CMakeLists.txt file passed as an argument and
  165. returns a list of all the perlasm() directives found in the file."""
  166. perlasms = []
  167. with open(cmakefile) as f:
  168. for line in f:
  169. line = line.strip()
  170. if not line.startswith('perlasm('):
  171. continue
  172. if not line.endswith(')'):
  173. raise ValueError('Bad perlasm line in %s' % cmakefile)
  174. # Remove "perlasm(" from start and ")" from end
  175. params = line[8:-1].split()
  176. if len(params) < 2:
  177. raise ValueError('Bad perlasm line in %s' % cmakefile)
  178. perlasms.append({
  179. 'extra_args': params[2:],
  180. 'input': os.path.join(os.path.dirname(cmakefile), params[1]),
  181. 'output': os.path.join(os.path.dirname(cmakefile), params[0]),
  182. })
  183. return perlasms
  184. def ReadPerlAsmOperations():
  185. """Returns a list of all perlasm() directives found in CMake config files in
  186. src/."""
  187. perlasms = []
  188. cmakefiles = FindCMakeFiles('src')
  189. for cmakefile in cmakefiles:
  190. perlasms.extend(ExtractPerlAsmFromCMakeFile(cmakefile))
  191. return perlasms
  192. def PerlAsm(output_filename, input_filename, perlasm_style, extra_args):
  193. """Runs the a perlasm script and puts the output into output_filename."""
  194. base_dir = os.path.dirname(output_filename)
  195. if not os.path.isdir(base_dir):
  196. os.makedirs(base_dir)
  197. output = subprocess.check_output(
  198. ['perl', input_filename, perlasm_style] + extra_args)
  199. with open(output_filename, 'w+') as out_file:
  200. out_file.write(output)
  201. def ArchForAsmFilename(filename):
  202. """Returns the architectures that a given asm file should be compiled for
  203. based on substrings in the filename."""
  204. if 'x86_64' in filename or 'avx2' in filename:
  205. return ['x86_64']
  206. elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
  207. return ['x86']
  208. elif 'armx' in filename:
  209. return ['arm', 'aarch64']
  210. elif 'armv8' in filename:
  211. return ['aarch64']
  212. elif 'arm' in filename:
  213. return ['arm']
  214. else:
  215. raise ValueError('Unknown arch for asm filename: ' + filename)
  216. def WriteAsmFiles(perlasms):
  217. """Generates asm files from perlasm directives for each supported OS x
  218. platform combination."""
  219. asmfiles = {}
  220. for osarch in OS_ARCH_COMBOS:
  221. (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
  222. key = (osname, arch)
  223. outDir = '%s-%s' % key
  224. for perlasm in perlasms:
  225. filename = os.path.basename(perlasm['input'])
  226. output = perlasm['output']
  227. if not output.startswith('src'):
  228. raise ValueError('output missing src: %s' % output)
  229. output = os.path.join(outDir, output[4:])
  230. output = output.replace('${ASM_EXT}', asm_ext)
  231. if arch in ArchForAsmFilename(filename):
  232. PerlAsm(output, perlasm['input'], perlasm_style,
  233. perlasm['extra_args'] + extra_args)
  234. asmfiles.setdefault(key, []).append(output)
  235. for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
  236. asmfiles.setdefault(key, []).extend(non_perl_asm_files)
  237. return asmfiles
  238. def main(platform):
  239. crypto_c_files = FindCFiles(os.path.join('src', 'crypto'), NoTests)
  240. ssl_c_files = FindCFiles(os.path.join('src', 'ssl'), NoTests)
  241. tool_cc_files = FindCFiles(os.path.join('src', 'tool'), NoTests)
  242. # Generate err_data.c
  243. with open('err_data.c', 'w+') as err_data:
  244. subprocess.check_call(['go', 'run', 'err_data_generate.go'],
  245. cwd=os.path.join('src', 'crypto', 'err'),
  246. stdout=err_data)
  247. crypto_c_files.append('err_data.c')
  248. test_support_cc_files = FindCFiles(os.path.join('src', 'crypto', 'test'),
  249. AllFiles)
  250. test_c_files = FindCFiles(os.path.join('src', 'crypto'), OnlyTests)
  251. test_c_files += FindCFiles(os.path.join('src', 'ssl'), OnlyTests)
  252. files = {
  253. 'crypto': crypto_c_files,
  254. 'ssl': ssl_c_files,
  255. 'tool': tool_cc_files,
  256. 'test': test_c_files,
  257. 'test_support': test_support_cc_files,
  258. }
  259. asm_outputs = sorted(WriteAsmFiles(ReadPerlAsmOperations()).iteritems())
  260. platform.WriteFiles(files, asm_outputs)
  261. return 0
  262. def Usage():
  263. print 'Usage: python %s [chromium|android]' % sys.argv[0]
  264. sys.exit(1)
  265. if __name__ == '__main__':
  266. if len(sys.argv) != 2:
  267. Usage()
  268. platform = None
  269. if sys.argv[1] == 'chromium':
  270. platform = Chromium()
  271. elif sys.argv[1] == 'android':
  272. platform = Android()
  273. else:
  274. Usage()
  275. sys.exit(main(platform))