create_recursive_library_for_cmake.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # Custom script is necessary because CMake does not yet support creating static libraries combined with dependencies
  2. # https://gitlab.kitware.com/cmake/cmake/-/issues/22975
  3. #
  4. # This script is intended to be used set as a CXX_LINKER_LAUNCHER property for recursive library targets.
  5. # It parses the linking command and transforms it to archiving commands combining static libraries from dependencies.
  6. import argparse
  7. import os
  8. import shlex
  9. import subprocess
  10. import sys
  11. import tempfile
  12. class Opts(object):
  13. def __init__(self, args):
  14. argparser = argparse.ArgumentParser(allow_abbrev=False)
  15. argparser.add_argument('--cmake-binary-dir', required=True)
  16. argparser.add_argument('--cmake-ar', required=True)
  17. argparser.add_argument('--cmake-ranlib', required=True)
  18. argparser.add_argument('--cmake-host-system-name', required=True)
  19. argparser.add_argument('--cmake-cxx-standard-libraries')
  20. argparser.add_argument('--global-part-suffix', required=True)
  21. self.parsed_args, other_args = argparser.parse_known_args(args=args)
  22. if len(other_args) < 2:
  23. # must contain at least '--linking-cmdline' and orginal linking tool name
  24. raise Exception('not enough arguments')
  25. if other_args[0] != '--linking-cmdline':
  26. raise Exception("expected '--linking-cmdline' arg, got {}".format(other_args[0]))
  27. self.is_msvc_compatible_linker = other_args[1].endswith('\\link.exe') or other_args[1].endswith('\\lld-link.exe')
  28. is_host_system_windows = self.parsed_args.cmake_host_system_name == 'Windows'
  29. std_libraries_to_exclude_from_input = (
  30. set(self.parsed_args.cmake_cxx_standard_libraries.split())
  31. if self.parsed_args.cmake_cxx_standard_libraries is not None
  32. else set()
  33. )
  34. msvc_preserved_option_prefixes = [
  35. 'machine:',
  36. 'nodefaultlib',
  37. 'nologo',
  38. ]
  39. self.preserved_options = []
  40. # these variables can contain paths absolute or relative to CMAKE_BINARY_DIR
  41. self.global_libs_and_objects_input = []
  42. self.non_global_libs_input = []
  43. self.output = None
  44. def is_external_library(path):
  45. """
  46. Check whether this library has been built in this CMake project or came from Conan-provided dependencies
  47. (these use absolute paths).
  48. If it is a library that is added from some other path (like CUDA) return True
  49. """
  50. return not (os.path.exists(path) or os.path.exists(os.path.join(self.parsed_args.cmake_binary_dir, path)))
  51. def process_input(args):
  52. i = 0
  53. is_in_whole_archive = False
  54. while i < len(args):
  55. arg = args[i]
  56. if is_host_system_windows and ((arg[0] == '/') or (arg[0] == '-')):
  57. arg_wo_specifier_lower = arg[1:].lower()
  58. if arg_wo_specifier_lower.startswith('out:'):
  59. self.output = arg[len('/out:') :]
  60. elif arg_wo_specifier_lower.startswith('wholearchive:'):
  61. lib_path = arg[len('/wholearchive:') :]
  62. if not is_external_library(lib_path):
  63. self.global_libs_and_objects_input.append(lib_path)
  64. else:
  65. for preserved_option_prefix in msvc_preserved_option_prefixes:
  66. if arg_wo_specifier_lower.startswith(preserved_option_prefix):
  67. self.preserved_options.append(arg)
  68. break
  69. # other flags are non-linking related and just ignored
  70. elif arg[0] == '-':
  71. if arg == '-o':
  72. if (i + 1) >= len(args):
  73. raise Exception('-o flag without an argument')
  74. self.output = args[i + 1]
  75. i += 1
  76. elif arg == '-Wl,--whole-archive':
  77. is_in_whole_archive = True
  78. elif arg == '-Wl,--no-whole-archive':
  79. is_in_whole_archive = False
  80. elif arg.startswith('-Wl,-force_load,'):
  81. lib_path = arg[len('-Wl,-force_load,') :]
  82. if not is_external_library(lib_path):
  83. self.global_libs_and_objects_input.append(lib_path)
  84. elif arg == '-isysroot':
  85. i += 1
  86. # other flags are non-linking related and just ignored
  87. elif arg[0] == '@':
  88. # response file with args
  89. with open(arg[1:]) as response_file:
  90. parsed_args = shlex.shlex(response_file, posix=False, punctuation_chars=False)
  91. parsed_args.whitespace_split = True
  92. args_in_response_file = list(arg.strip('"') for arg in parsed_args)
  93. process_input(args_in_response_file)
  94. elif not is_external_library(arg):
  95. if is_in_whole_archive or arg.endswith('.o') or arg.endswith('.obj'):
  96. self.global_libs_and_objects_input.append(arg)
  97. elif arg not in std_libraries_to_exclude_from_input:
  98. self.non_global_libs_input.append(arg)
  99. i += 1
  100. process_input(other_args[2:])
  101. if self.output is None:
  102. raise Exception("No output specified")
  103. if (len(self.global_libs_and_objects_input) == 0) and (len(self.non_global_libs_input) == 0):
  104. raise Exception("List of input objects and libraries is empty")
  105. class FilesCombiner(object):
  106. def __init__(self, opts):
  107. self.opts = opts
  108. archiver_tool_path = opts.parsed_args.cmake_ar
  109. if sys.platform.startswith('darwin'):
  110. # force LIBTOOL even if CMAKE_AR is defined because 'ar' under Darwin does not contain the necessary options
  111. arch_type = 'LIBTOOL'
  112. archiver_tool_path = 'libtool'
  113. elif opts.is_msvc_compatible_linker:
  114. arch_type = 'LIB'
  115. elif opts.parsed_args.cmake_ar.endswith('llvm-ar'):
  116. arch_type = 'LLVM_AR'
  117. elif opts.parsed_args.cmake_ar.endswith('ar'):
  118. arch_type = 'GNU_AR'
  119. else:
  120. raise Exception('Unsupported arch type for CMAKE_AR={}'.format(opts.parsed_args.cmake_ar))
  121. self.archiving_cmd_prefix = [
  122. sys.executable,
  123. os.path.join(os.path.dirname(os.path.abspath(__file__)), 'link_lib.py'),
  124. archiver_tool_path,
  125. arch_type,
  126. 'gnu', # llvm_ar_format, used only if arch_type == 'LLVM_AR'
  127. opts.parsed_args.cmake_binary_dir,
  128. 'None', # plugin. Unused for now
  129. ]
  130. # the remaining archiving cmd args are [output, .. input .. ]
  131. def do(self, output, input_list):
  132. input_file_path = None
  133. try:
  134. if self.opts.is_msvc_compatible_linker:
  135. # use response file for input (because of Windows cmdline length limitations)
  136. # can't use NamedTemporaryFile because of permissions issues on Windows
  137. input_file_fd, input_file_path = tempfile.mkstemp()
  138. try:
  139. input_file = os.fdopen(input_file_fd, 'w')
  140. for input in input_list:
  141. if ' ' in input:
  142. input_file.write('"{}" '.format(input))
  143. else:
  144. input_file.write('{} '.format(input))
  145. input_file.flush()
  146. finally:
  147. os.close(input_file_fd)
  148. input_args = ['@' + input_file_path]
  149. else:
  150. input_args = input_list
  151. cmd = self.archiving_cmd_prefix + [output] + self.opts.preserved_options + input_args
  152. subprocess.check_call(cmd)
  153. finally:
  154. if input_file_path is not None:
  155. os.remove(input_file_path)
  156. if not self.opts.is_msvc_compatible_linker:
  157. subprocess.check_call([self.opts.parsed_args.cmake_ranlib, output])
  158. if __name__ == "__main__":
  159. opts = Opts(sys.argv[1:])
  160. output_prefix, output_ext = os.path.splitext(opts.output)
  161. globals_output = output_prefix + opts.parsed_args.global_part_suffix + output_ext
  162. if os.path.exists(globals_output):
  163. os.remove(globals_output)
  164. if os.path.exists(opts.output):
  165. os.remove(opts.output)
  166. files_combiner = FilesCombiner(opts)
  167. if len(opts.global_libs_and_objects_input) > 0:
  168. files_combiner.do(globals_output, opts.global_libs_and_objects_input)
  169. if len(opts.non_global_libs_input) > 0:
  170. files_combiner.do(opts.output, opts.non_global_libs_input)