4601336e89bfcee487357c429348a1ec024a2fac31224c36abbaed117d5cf99d0e12f5fe875b70b6a7fc7818c8ea88834bcde21d4e71273c303bbd309d6cbd 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. # Copyright (c) 2013 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """cmake output module
  5. This module is under development and should be considered experimental.
  6. This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is
  7. created for each configuration.
  8. This module's original purpose was to support editing in IDEs like KDevelop
  9. which use CMake for project management. It is also possible to use CMake to
  10. generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator
  11. will convert the CMakeLists.txt to a code::blocks cbp for the editor to read,
  12. but build using CMake. As a result QtCreator editor is unaware of compiler
  13. defines. The generated CMakeLists.txt can also be used to build on Linux. There
  14. is currently no support for building on platforms other than Linux.
  15. The generated CMakeLists.txt should properly compile all projects. However,
  16. there is a mismatch between gyp and cmake with regard to linking. All attempts
  17. are made to work around this, but CMake sometimes sees -Wl,--start-group as a
  18. library and incorrectly repeats it. As a result the output of this generator
  19. should not be relied on for building.
  20. When using with kdevelop, use version 4.4+. Previous versions of kdevelop will
  21. not be able to find the header file directories described in the generated
  22. CMakeLists.txt file.
  23. """
  24. import multiprocessing
  25. import os
  26. import signal
  27. import subprocess
  28. import gyp.common
  29. import gyp.xcode_emulation
  30. _maketrans = str.maketrans
  31. generator_default_variables = {
  32. "EXECUTABLE_PREFIX": "",
  33. "EXECUTABLE_SUFFIX": "",
  34. "STATIC_LIB_PREFIX": "lib",
  35. "STATIC_LIB_SUFFIX": ".a",
  36. "SHARED_LIB_PREFIX": "lib",
  37. "SHARED_LIB_SUFFIX": ".so",
  38. "SHARED_LIB_DIR": "${builddir}/lib.${TOOLSET}",
  39. "LIB_DIR": "${obj}.${TOOLSET}",
  40. "INTERMEDIATE_DIR": "${obj}.${TOOLSET}/${TARGET}/geni",
  41. "SHARED_INTERMEDIATE_DIR": "${obj}/gen",
  42. "PRODUCT_DIR": "${builddir}",
  43. "RULE_INPUT_PATH": "${RULE_INPUT_PATH}",
  44. "RULE_INPUT_DIRNAME": "${RULE_INPUT_DIRNAME}",
  45. "RULE_INPUT_NAME": "${RULE_INPUT_NAME}",
  46. "RULE_INPUT_ROOT": "${RULE_INPUT_ROOT}",
  47. "RULE_INPUT_EXT": "${RULE_INPUT_EXT}",
  48. "CONFIGURATION_NAME": "${configuration}",
  49. }
  50. FULL_PATH_VARS = ("${CMAKE_CURRENT_LIST_DIR}", "${builddir}", "${obj}")
  51. generator_supports_multiple_toolsets = True
  52. generator_wants_static_library_dependencies_adjusted = True
  53. COMPILABLE_EXTENSIONS = {
  54. ".c": "cc",
  55. ".cc": "cxx",
  56. ".cpp": "cxx",
  57. ".cxx": "cxx",
  58. ".s": "s", # cc
  59. ".S": "s", # cc
  60. }
  61. def RemovePrefix(a, prefix):
  62. """Returns 'a' without 'prefix' if it starts with 'prefix'."""
  63. return a[len(prefix) :] if a.startswith(prefix) else a
  64. def CalculateVariables(default_variables, params):
  65. """Calculate additional variables for use in the build (called by gyp)."""
  66. default_variables.setdefault("OS", gyp.common.GetFlavor(params))
  67. def Compilable(filename):
  68. """Return true if the file is compilable (should be in OBJS)."""
  69. return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS)
  70. def Linkable(filename):
  71. """Return true if the file is linkable (should be on the link line)."""
  72. return filename.endswith(".o")
  73. def NormjoinPathForceCMakeSource(base_path, rel_path):
  74. """Resolves rel_path against base_path and returns the result.
  75. If rel_path is an absolute path it is returned unchanged.
  76. Otherwise it is resolved against base_path and normalized.
  77. If the result is a relative path, it is forced to be relative to the
  78. CMakeLists.txt.
  79. """
  80. if os.path.isabs(rel_path):
  81. return rel_path
  82. if any(rel_path.startswith(var) for var in FULL_PATH_VARS):
  83. return rel_path
  84. # TODO: do we need to check base_path for absolute variables as well?
  85. return os.path.join(
  86. "${CMAKE_CURRENT_LIST_DIR}", os.path.normpath(os.path.join(base_path, rel_path))
  87. )
  88. def NormjoinPath(base_path, rel_path):
  89. """Resolves rel_path against base_path and returns the result.
  90. TODO: what is this really used for?
  91. If rel_path begins with '$' it is returned unchanged.
  92. Otherwise it is resolved against base_path if relative, then normalized.
  93. """
  94. if rel_path.startswith("$") and not rel_path.startswith("${configuration}"):
  95. return rel_path
  96. return os.path.normpath(os.path.join(base_path, rel_path))
  97. def CMakeStringEscape(a):
  98. """Escapes the string 'a' for use inside a CMake string.
  99. This means escaping
  100. '\' otherwise it may be seen as modifying the next character
  101. '"' otherwise it will end the string
  102. ';' otherwise the string becomes a list
  103. The following do not need to be escaped
  104. '#' when the lexer is in string state, this does not start a comment
  105. The following are yet unknown
  106. '$' generator variables (like ${obj}) must not be escaped,
  107. but text $ should be escaped
  108. what is wanted is to know which $ come from generator variables
  109. """
  110. return a.replace("\\", "\\\\").replace(";", "\\;").replace('"', '\\"')
  111. def SetFileProperty(output, source_name, property_name, values, sep):
  112. """Given a set of source file, sets the given property on them."""
  113. output.write("set_source_files_properties(")
  114. output.write(source_name)
  115. output.write(" PROPERTIES ")
  116. output.write(property_name)
  117. output.write(' "')
  118. for value in values:
  119. output.write(CMakeStringEscape(value))
  120. output.write(sep)
  121. output.write('")\n')
  122. def SetFilesProperty(output, variable, property_name, values, sep):
  123. """Given a set of source files, sets the given property on them."""
  124. output.write("set_source_files_properties(")
  125. WriteVariable(output, variable)
  126. output.write(" PROPERTIES ")
  127. output.write(property_name)
  128. output.write(' "')
  129. for value in values:
  130. output.write(CMakeStringEscape(value))
  131. output.write(sep)
  132. output.write('")\n')
  133. def SetTargetProperty(output, target_name, property_name, values, sep=""):
  134. """Given a target, sets the given property."""
  135. output.write("set_target_properties(")
  136. output.write(target_name)
  137. output.write(" PROPERTIES ")
  138. output.write(property_name)
  139. output.write(' "')
  140. for value in values:
  141. output.write(CMakeStringEscape(value))
  142. output.write(sep)
  143. output.write('")\n')
  144. def SetVariable(output, variable_name, value):
  145. """Sets a CMake variable."""
  146. output.write("set(")
  147. output.write(variable_name)
  148. output.write(' "')
  149. output.write(CMakeStringEscape(value))
  150. output.write('")\n')
  151. def SetVariableList(output, variable_name, values):
  152. """Sets a CMake variable to a list."""
  153. if not values:
  154. return SetVariable(output, variable_name, "")
  155. if len(values) == 1:
  156. return SetVariable(output, variable_name, values[0])
  157. output.write("list(APPEND ")
  158. output.write(variable_name)
  159. output.write('\n "')
  160. output.write('"\n "'.join([CMakeStringEscape(value) for value in values]))
  161. output.write('")\n')
  162. def UnsetVariable(output, variable_name):
  163. """Unsets a CMake variable."""
  164. output.write("unset(")
  165. output.write(variable_name)
  166. output.write(")\n")
  167. def WriteVariable(output, variable_name, prepend=None):
  168. if prepend:
  169. output.write(prepend)
  170. output.write("${")
  171. output.write(variable_name)
  172. output.write("}")
  173. class CMakeTargetType:
  174. def __init__(self, command, modifier, property_modifier):
  175. self.command = command
  176. self.modifier = modifier
  177. self.property_modifier = property_modifier
  178. cmake_target_type_from_gyp_target_type = {
  179. "executable": CMakeTargetType("add_executable", None, "RUNTIME"),
  180. "static_library": CMakeTargetType("add_library", "STATIC", "ARCHIVE"),
  181. "shared_library": CMakeTargetType("add_library", "SHARED", "LIBRARY"),
  182. "loadable_module": CMakeTargetType("add_library", "MODULE", "LIBRARY"),
  183. "none": CMakeTargetType("add_custom_target", "SOURCES", None),
  184. }
  185. def StringToCMakeTargetName(a):
  186. """Converts the given string 'a' to a valid CMake target name.
  187. All invalid characters are replaced by '_'.
  188. Invalid for cmake: ' ', '/', '(', ')', '"'
  189. Invalid for make: ':'
  190. Invalid for unknown reasons but cause failures: '.'
  191. """
  192. return a.translate(_maketrans(' /():."', "_______"))
  193. def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, output):
  194. """Write CMake for the 'actions' in the target.
  195. Args:
  196. target_name: the name of the CMake target being generated.
  197. actions: the Gyp 'actions' dict for this target.
  198. extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
  199. extra_deps: [<cmake_target>] to append with generated targets.
  200. path_to_gyp: relative path from CMakeLists.txt being generated to
  201. the Gyp file in which the target being generated is defined.
  202. """
  203. for action in actions:
  204. action_name = StringToCMakeTargetName(action["action_name"])
  205. action_target_name = f"{target_name}__{action_name}"
  206. inputs = action["inputs"]
  207. inputs_name = action_target_name + "__input"
  208. SetVariableList(
  209. output,
  210. inputs_name,
  211. [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs],
  212. )
  213. outputs = action["outputs"]
  214. cmake_outputs = [
  215. NormjoinPathForceCMakeSource(path_to_gyp, out) for out in outputs
  216. ]
  217. outputs_name = action_target_name + "__output"
  218. SetVariableList(output, outputs_name, cmake_outputs)
  219. # Build up a list of outputs.
  220. # Collect the output dirs we'll need.
  221. dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir}
  222. if int(action.get("process_outputs_as_sources", False)):
  223. extra_sources.extend(zip(cmake_outputs, outputs))
  224. # add_custom_command
  225. output.write("add_custom_command(OUTPUT ")
  226. WriteVariable(output, outputs_name)
  227. output.write("\n")
  228. if len(dirs) > 0:
  229. for directory in dirs:
  230. output.write(" COMMAND ${CMAKE_COMMAND} -E make_directory ")
  231. output.write(directory)
  232. output.write("\n")
  233. output.write(" COMMAND ")
  234. output.write(gyp.common.EncodePOSIXShellList(action["action"]))
  235. output.write("\n")
  236. output.write(" DEPENDS ")
  237. WriteVariable(output, inputs_name)
  238. output.write("\n")
  239. output.write(" WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
  240. output.write(path_to_gyp)
  241. output.write("\n")
  242. output.write(" COMMENT ")
  243. if "message" in action:
  244. output.write(action["message"])
  245. else:
  246. output.write(action_target_name)
  247. output.write("\n")
  248. output.write(" VERBATIM\n")
  249. output.write(")\n")
  250. # add_custom_target
  251. output.write("add_custom_target(")
  252. output.write(action_target_name)
  253. output.write("\n DEPENDS ")
  254. WriteVariable(output, outputs_name)
  255. output.write("\n SOURCES ")
  256. WriteVariable(output, inputs_name)
  257. output.write("\n)\n")
  258. extra_deps.append(action_target_name)
  259. def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source):
  260. if rel_path.startswith(("${RULE_INPUT_PATH}", "${RULE_INPUT_DIRNAME}")):
  261. if any(rule_source.startswith(var) for var in FULL_PATH_VARS):
  262. return rel_path
  263. return NormjoinPathForceCMakeSource(base_path, rel_path)
  264. def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output):
  265. """Write CMake for the 'rules' in the target.
  266. Args:
  267. target_name: the name of the CMake target being generated.
  268. actions: the Gyp 'actions' dict for this target.
  269. extra_sources: [(<cmake_src>, <src>)] to append with generated source files.
  270. extra_deps: [<cmake_target>] to append with generated targets.
  271. path_to_gyp: relative path from CMakeLists.txt being generated to
  272. the Gyp file in which the target being generated is defined.
  273. """
  274. for rule in rules:
  275. rule_name = StringToCMakeTargetName(target_name + "__" + rule["rule_name"])
  276. inputs = rule.get("inputs", [])
  277. inputs_name = rule_name + "__input"
  278. SetVariableList(
  279. output,
  280. inputs_name,
  281. [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs],
  282. )
  283. outputs = rule["outputs"]
  284. var_outputs = []
  285. for count, rule_source in enumerate(rule.get("rule_sources", [])):
  286. action_name = rule_name + "_" + str(count)
  287. rule_source_dirname, rule_source_basename = os.path.split(rule_source)
  288. rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename)
  289. SetVariable(output, "RULE_INPUT_PATH", rule_source)
  290. SetVariable(output, "RULE_INPUT_DIRNAME", rule_source_dirname)
  291. SetVariable(output, "RULE_INPUT_NAME", rule_source_basename)
  292. SetVariable(output, "RULE_INPUT_ROOT", rule_source_root)
  293. SetVariable(output, "RULE_INPUT_EXT", rule_source_ext)
  294. # Build up a list of outputs.
  295. # Collect the output dirs we'll need.
  296. dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir}
  297. # Create variables for the output, as 'local' variable will be unset.
  298. these_outputs = []
  299. for output_index, out in enumerate(outputs):
  300. output_name = action_name + "_" + str(output_index)
  301. SetVariable(
  302. output,
  303. output_name,
  304. NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source),
  305. )
  306. if int(rule.get("process_outputs_as_sources", False)):
  307. extra_sources.append(("${" + output_name + "}", out))
  308. these_outputs.append("${" + output_name + "}")
  309. var_outputs.append("${" + output_name + "}")
  310. # add_custom_command
  311. output.write("add_custom_command(OUTPUT\n")
  312. for out in these_outputs:
  313. output.write(" ")
  314. output.write(out)
  315. output.write("\n")
  316. for directory in dirs:
  317. output.write(" COMMAND ${CMAKE_COMMAND} -E make_directory ")
  318. output.write(directory)
  319. output.write("\n")
  320. output.write(" COMMAND ")
  321. output.write(gyp.common.EncodePOSIXShellList(rule["action"]))
  322. output.write("\n")
  323. output.write(" DEPENDS ")
  324. WriteVariable(output, inputs_name)
  325. output.write(" ")
  326. output.write(NormjoinPath(path_to_gyp, rule_source))
  327. output.write("\n")
  328. # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives.
  329. # The cwd is the current build directory.
  330. output.write(" WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
  331. output.write(path_to_gyp)
  332. output.write("\n")
  333. output.write(" COMMENT ")
  334. if "message" in rule:
  335. output.write(rule["message"])
  336. else:
  337. output.write(action_name)
  338. output.write("\n")
  339. output.write(" VERBATIM\n")
  340. output.write(")\n")
  341. UnsetVariable(output, "RULE_INPUT_PATH")
  342. UnsetVariable(output, "RULE_INPUT_DIRNAME")
  343. UnsetVariable(output, "RULE_INPUT_NAME")
  344. UnsetVariable(output, "RULE_INPUT_ROOT")
  345. UnsetVariable(output, "RULE_INPUT_EXT")
  346. # add_custom_target
  347. output.write("add_custom_target(")
  348. output.write(rule_name)
  349. output.write(" DEPENDS\n")
  350. for out in var_outputs:
  351. output.write(" ")
  352. output.write(out)
  353. output.write("\n")
  354. output.write("SOURCES ")
  355. WriteVariable(output, inputs_name)
  356. output.write("\n")
  357. for rule_source in rule.get("rule_sources", []):
  358. output.write(" ")
  359. output.write(NormjoinPath(path_to_gyp, rule_source))
  360. output.write("\n")
  361. output.write(")\n")
  362. extra_deps.append(rule_name)
  363. def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output):
  364. """Write CMake for the 'copies' in the target.
  365. Args:
  366. target_name: the name of the CMake target being generated.
  367. actions: the Gyp 'actions' dict for this target.
  368. extra_deps: [<cmake_target>] to append with generated targets.
  369. path_to_gyp: relative path from CMakeLists.txt being generated to
  370. the Gyp file in which the target being generated is defined.
  371. """
  372. copy_name = target_name + "__copies"
  373. # CMake gets upset with custom targets with OUTPUT which specify no output.
  374. have_copies = any(copy["files"] for copy in copies)
  375. if not have_copies:
  376. output.write("add_custom_target(")
  377. output.write(copy_name)
  378. output.write(")\n")
  379. extra_deps.append(copy_name)
  380. return
  381. class Copy:
  382. def __init__(self, ext, command):
  383. self.cmake_inputs = []
  384. self.cmake_outputs = []
  385. self.gyp_inputs = []
  386. self.gyp_outputs = []
  387. self.ext = ext
  388. self.inputs_name = None
  389. self.outputs_name = None
  390. self.command = command
  391. file_copy = Copy("", "copy")
  392. dir_copy = Copy("_dirs", "copy_directory")
  393. for copy in copies:
  394. files = copy["files"]
  395. destination = copy["destination"]
  396. for src in files:
  397. path = os.path.normpath(src)
  398. basename = os.path.split(path)[1]
  399. dst = os.path.join(destination, basename)
  400. copy = file_copy if os.path.basename(src) else dir_copy
  401. copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src))
  402. copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst))
  403. copy.gyp_inputs.append(src)
  404. copy.gyp_outputs.append(dst)
  405. for copy in (file_copy, dir_copy):
  406. if copy.cmake_inputs:
  407. copy.inputs_name = copy_name + "__input" + copy.ext
  408. SetVariableList(output, copy.inputs_name, copy.cmake_inputs)
  409. copy.outputs_name = copy_name + "__output" + copy.ext
  410. SetVariableList(output, copy.outputs_name, copy.cmake_outputs)
  411. # add_custom_command
  412. output.write("add_custom_command(\n")
  413. output.write("OUTPUT")
  414. for copy in (file_copy, dir_copy):
  415. if copy.outputs_name:
  416. WriteVariable(output, copy.outputs_name, " ")
  417. output.write("\n")
  418. for copy in (file_copy, dir_copy):
  419. for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs):
  420. # 'cmake -E copy src dst' will create the 'dst' directory if needed.
  421. output.write("COMMAND ${CMAKE_COMMAND} -E %s " % copy.command)
  422. output.write(src)
  423. output.write(" ")
  424. output.write(dst)
  425. output.write("\n")
  426. output.write("DEPENDS")
  427. for copy in (file_copy, dir_copy):
  428. if copy.inputs_name:
  429. WriteVariable(output, copy.inputs_name, " ")
  430. output.write("\n")
  431. output.write("WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/")
  432. output.write(path_to_gyp)
  433. output.write("\n")
  434. output.write("COMMENT Copying for ")
  435. output.write(target_name)
  436. output.write("\n")
  437. output.write("VERBATIM\n")
  438. output.write(")\n")
  439. # add_custom_target
  440. output.write("add_custom_target(")
  441. output.write(copy_name)
  442. output.write("\n DEPENDS")
  443. for copy in (file_copy, dir_copy):
  444. if copy.outputs_name:
  445. WriteVariable(output, copy.outputs_name, " ")
  446. output.write("\n SOURCES")
  447. if file_copy.inputs_name:
  448. WriteVariable(output, file_copy.inputs_name, " ")
  449. output.write("\n)\n")
  450. extra_deps.append(copy_name)
  451. def CreateCMakeTargetBaseName(qualified_target):
  452. """This is the name we would like the target to have."""
  453. _, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget(
  454. qualified_target
  455. )
  456. cmake_target_base_name = gyp_target_name
  457. if gyp_target_toolset and gyp_target_toolset != "target":
  458. cmake_target_base_name += "_" + gyp_target_toolset
  459. return StringToCMakeTargetName(cmake_target_base_name)
  460. def CreateCMakeTargetFullName(qualified_target):
  461. """An unambiguous name for the target."""
  462. gyp_file, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget(
  463. qualified_target
  464. )
  465. cmake_target_full_name = gyp_file + ":" + gyp_target_name
  466. if gyp_target_toolset and gyp_target_toolset != "target":
  467. cmake_target_full_name += "_" + gyp_target_toolset
  468. return StringToCMakeTargetName(cmake_target_full_name)
  469. class CMakeNamer:
  470. """Converts Gyp target names into CMake target names.
  471. CMake requires that target names be globally unique. One way to ensure
  472. this is to fully qualify the names of the targets. Unfortunately, this
  473. ends up with all targets looking like "chrome_chrome_gyp_chrome" instead
  474. of just "chrome". If this generator were only interested in building, it
  475. would be possible to fully qualify all target names, then create
  476. unqualified target names which depend on all qualified targets which
  477. should have had that name. This is more or less what the 'make' generator
  478. does with aliases. However, one goal of this generator is to create CMake
  479. files for use with IDEs, and fully qualified names are not as user
  480. friendly.
  481. Since target name collision is rare, we do the above only when required.
  482. Toolset variants are always qualified from the base, as this is required for
  483. building. However, it also makes sense for an IDE, as it is possible for
  484. defines to be different.
  485. """
  486. def __init__(self, target_list):
  487. self.cmake_target_base_names_conflicting = set()
  488. cmake_target_base_names_seen = set()
  489. for qualified_target in target_list:
  490. cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target)
  491. if cmake_target_base_name not in cmake_target_base_names_seen:
  492. cmake_target_base_names_seen.add(cmake_target_base_name)
  493. else:
  494. self.cmake_target_base_names_conflicting.add(cmake_target_base_name)
  495. def CreateCMakeTargetName(self, qualified_target):
  496. base_name = CreateCMakeTargetBaseName(qualified_target)
  497. if base_name in self.cmake_target_base_names_conflicting:
  498. return CreateCMakeTargetFullName(qualified_target)
  499. return base_name
  500. def WriteTarget(
  501. namer,
  502. qualified_target,
  503. target_dicts,
  504. build_dir,
  505. config_to_use,
  506. options,
  507. generator_flags,
  508. all_qualified_targets,
  509. flavor,
  510. output,
  511. ):
  512. # The make generator does this always.
  513. # TODO: It would be nice to be able to tell CMake all dependencies.
  514. circular_libs = generator_flags.get("circular", True)
  515. if not generator_flags.get("standalone", False):
  516. output.write("\n#")
  517. output.write(qualified_target)
  518. output.write("\n")
  519. gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
  520. rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir)
  521. rel_gyp_dir = os.path.dirname(rel_gyp_file)
  522. # Relative path from build dir to top dir.
  523. build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
  524. # Relative path from build dir to gyp dir.
  525. build_to_gyp = os.path.join(build_to_top, rel_gyp_dir)
  526. path_from_cmakelists_to_gyp = build_to_gyp
  527. spec = target_dicts.get(qualified_target, {})
  528. config = spec.get("configurations", {}).get(config_to_use, {})
  529. xcode_settings = None
  530. if flavor == "mac":
  531. xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
  532. target_name = spec.get("target_name", "<missing target name>")
  533. target_type = spec.get("type", "<missing target type>")
  534. target_toolset = spec.get("toolset")
  535. cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type)
  536. if cmake_target_type is None:
  537. print(
  538. "Target %s has unknown target type %s, skipping."
  539. % (target_name, target_type)
  540. )
  541. return
  542. SetVariable(output, "TARGET", target_name)
  543. SetVariable(output, "TOOLSET", target_toolset)
  544. cmake_target_name = namer.CreateCMakeTargetName(qualified_target)
  545. extra_sources = []
  546. extra_deps = []
  547. # Actions must come first, since they can generate more OBJs for use below.
  548. if "actions" in spec:
  549. WriteActions(
  550. cmake_target_name,
  551. spec["actions"],
  552. extra_sources,
  553. extra_deps,
  554. path_from_cmakelists_to_gyp,
  555. output,
  556. )
  557. # Rules must be early like actions.
  558. if "rules" in spec:
  559. WriteRules(
  560. cmake_target_name,
  561. spec["rules"],
  562. extra_sources,
  563. extra_deps,
  564. path_from_cmakelists_to_gyp,
  565. output,
  566. )
  567. # Copies
  568. if "copies" in spec:
  569. WriteCopies(
  570. cmake_target_name,
  571. spec["copies"],
  572. extra_deps,
  573. path_from_cmakelists_to_gyp,
  574. output,
  575. )
  576. # Target and sources
  577. srcs = spec.get("sources", [])
  578. # Gyp separates the sheep from the goats based on file extensions.
  579. # A full separation is done here because of flag handing (see below).
  580. s_sources = []
  581. c_sources = []
  582. cxx_sources = []
  583. linkable_sources = []
  584. other_sources = []
  585. for src in srcs:
  586. _, ext = os.path.splitext(src)
  587. src_type = COMPILABLE_EXTENSIONS.get(ext, None)
  588. src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src)
  589. if src_type == "s":
  590. s_sources.append(src_norm_path)
  591. elif src_type == "cc":
  592. c_sources.append(src_norm_path)
  593. elif src_type == "cxx":
  594. cxx_sources.append(src_norm_path)
  595. elif Linkable(ext):
  596. linkable_sources.append(src_norm_path)
  597. else:
  598. other_sources.append(src_norm_path)
  599. for extra_source in extra_sources:
  600. src, real_source = extra_source
  601. _, ext = os.path.splitext(real_source)
  602. src_type = COMPILABLE_EXTENSIONS.get(ext, None)
  603. if src_type == "s":
  604. s_sources.append(src)
  605. elif src_type == "cc":
  606. c_sources.append(src)
  607. elif src_type == "cxx":
  608. cxx_sources.append(src)
  609. elif Linkable(ext):
  610. linkable_sources.append(src)
  611. else:
  612. other_sources.append(src)
  613. s_sources_name = None
  614. if s_sources:
  615. s_sources_name = cmake_target_name + "__asm_srcs"
  616. SetVariableList(output, s_sources_name, s_sources)
  617. c_sources_name = None
  618. if c_sources:
  619. c_sources_name = cmake_target_name + "__c_srcs"
  620. SetVariableList(output, c_sources_name, c_sources)
  621. cxx_sources_name = None
  622. if cxx_sources:
  623. cxx_sources_name = cmake_target_name + "__cxx_srcs"
  624. SetVariableList(output, cxx_sources_name, cxx_sources)
  625. linkable_sources_name = None
  626. if linkable_sources:
  627. linkable_sources_name = cmake_target_name + "__linkable_srcs"
  628. SetVariableList(output, linkable_sources_name, linkable_sources)
  629. other_sources_name = None
  630. if other_sources:
  631. other_sources_name = cmake_target_name + "__other_srcs"
  632. SetVariableList(output, other_sources_name, other_sources)
  633. # CMake gets upset when executable targets provide no sources.
  634. # http://www.cmake.org/pipermail/cmake/2010-July/038461.html
  635. dummy_sources_name = None
  636. has_sources = (
  637. s_sources_name
  638. or c_sources_name
  639. or cxx_sources_name
  640. or linkable_sources_name
  641. or other_sources_name
  642. )
  643. if target_type == "executable" and not has_sources:
  644. dummy_sources_name = cmake_target_name + "__dummy_srcs"
  645. SetVariable(
  646. output, dummy_sources_name, "${obj}.${TOOLSET}/${TARGET}/genc/dummy.c"
  647. )
  648. output.write('if(NOT EXISTS "')
  649. WriteVariable(output, dummy_sources_name)
  650. output.write('")\n')
  651. output.write(' file(WRITE "')
  652. WriteVariable(output, dummy_sources_name)
  653. output.write('" "")\n')
  654. output.write("endif()\n")
  655. # CMake is opposed to setting linker directories and considers the practice
  656. # of setting linker directories dangerous. Instead, it favors the use of
  657. # find_library and passing absolute paths to target_link_libraries.
  658. # However, CMake does provide the command link_directories, which adds
  659. # link directories to targets defined after it is called.
  660. # As a result, link_directories must come before the target definition.
  661. # CMake unfortunately has no means of removing entries from LINK_DIRECTORIES.
  662. library_dirs = config.get("library_dirs")
  663. if library_dirs is not None:
  664. output.write("link_directories(")
  665. for library_dir in library_dirs:
  666. output.write(" ")
  667. output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir))
  668. output.write("\n")
  669. output.write(")\n")
  670. output.write(cmake_target_type.command)
  671. output.write("(")
  672. output.write(cmake_target_name)
  673. if cmake_target_type.modifier is not None:
  674. output.write(" ")
  675. output.write(cmake_target_type.modifier)
  676. if s_sources_name:
  677. WriteVariable(output, s_sources_name, " ")
  678. if c_sources_name:
  679. WriteVariable(output, c_sources_name, " ")
  680. if cxx_sources_name:
  681. WriteVariable(output, cxx_sources_name, " ")
  682. if linkable_sources_name:
  683. WriteVariable(output, linkable_sources_name, " ")
  684. if other_sources_name:
  685. WriteVariable(output, other_sources_name, " ")
  686. if dummy_sources_name:
  687. WriteVariable(output, dummy_sources_name, " ")
  688. output.write(")\n")
  689. # Let CMake know if the 'all' target should depend on this target.
  690. exclude_from_all = (
  691. "TRUE" if qualified_target not in all_qualified_targets else "FALSE"
  692. )
  693. SetTargetProperty(output, cmake_target_name, "EXCLUDE_FROM_ALL", exclude_from_all)
  694. for extra_target_name in extra_deps:
  695. SetTargetProperty(
  696. output, extra_target_name, "EXCLUDE_FROM_ALL", exclude_from_all
  697. )
  698. # Output name and location.
  699. if target_type != "none":
  700. # Link as 'C' if there are no other files
  701. if not c_sources and not cxx_sources:
  702. SetTargetProperty(output, cmake_target_name, "LINKER_LANGUAGE", ["C"])
  703. # Mark uncompiled sources as uncompiled.
  704. if other_sources_name:
  705. output.write("set_source_files_properties(")
  706. WriteVariable(output, other_sources_name, "")
  707. output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n')
  708. # Mark object sources as linkable.
  709. if linkable_sources_name:
  710. output.write("set_source_files_properties(")
  711. WriteVariable(output, other_sources_name, "")
  712. output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n')
  713. # Output directory
  714. target_output_directory = spec.get("product_dir")
  715. if target_output_directory is None:
  716. if target_type in ("executable", "loadable_module"):
  717. target_output_directory = generator_default_variables["PRODUCT_DIR"]
  718. elif target_type == "shared_library":
  719. target_output_directory = "${builddir}/lib.${TOOLSET}"
  720. elif spec.get("standalone_static_library", False):
  721. target_output_directory = generator_default_variables["PRODUCT_DIR"]
  722. else:
  723. base_path = gyp.common.RelativePath(
  724. os.path.dirname(gyp_file), options.toplevel_dir
  725. )
  726. target_output_directory = "${obj}.${TOOLSET}"
  727. target_output_directory = os.path.join(
  728. target_output_directory, base_path
  729. )
  730. cmake_target_output_directory = NormjoinPathForceCMakeSource(
  731. path_from_cmakelists_to_gyp, target_output_directory
  732. )
  733. SetTargetProperty(
  734. output,
  735. cmake_target_name,
  736. cmake_target_type.property_modifier + "_OUTPUT_DIRECTORY",
  737. cmake_target_output_directory,
  738. )
  739. # Output name
  740. default_product_prefix = ""
  741. default_product_name = target_name
  742. default_product_ext = ""
  743. if target_type == "static_library":
  744. static_library_prefix = generator_default_variables["STATIC_LIB_PREFIX"]
  745. default_product_name = RemovePrefix(
  746. default_product_name, static_library_prefix
  747. )
  748. default_product_prefix = static_library_prefix
  749. default_product_ext = generator_default_variables["STATIC_LIB_SUFFIX"]
  750. elif target_type in ("loadable_module", "shared_library"):
  751. shared_library_prefix = generator_default_variables["SHARED_LIB_PREFIX"]
  752. default_product_name = RemovePrefix(
  753. default_product_name, shared_library_prefix
  754. )
  755. default_product_prefix = shared_library_prefix
  756. default_product_ext = generator_default_variables["SHARED_LIB_SUFFIX"]
  757. elif target_type != "executable":
  758. print(
  759. "ERROR: What output file should be generated?",
  760. "type",
  761. target_type,
  762. "target",
  763. target_name,
  764. )
  765. product_prefix = spec.get("product_prefix", default_product_prefix)
  766. product_name = spec.get("product_name", default_product_name)
  767. product_ext = spec.get("product_extension")
  768. product_ext = "." + product_ext if product_ext else default_product_ext
  769. SetTargetProperty(output, cmake_target_name, "PREFIX", product_prefix)
  770. SetTargetProperty(
  771. output,
  772. cmake_target_name,
  773. cmake_target_type.property_modifier + "_OUTPUT_NAME",
  774. product_name,
  775. )
  776. SetTargetProperty(output, cmake_target_name, "SUFFIX", product_ext)
  777. # Make the output of this target referenceable as a source.
  778. cmake_target_output_basename = product_prefix + product_name + product_ext
  779. cmake_target_output = os.path.join(
  780. cmake_target_output_directory, cmake_target_output_basename
  781. )
  782. SetFileProperty(output, cmake_target_output, "GENERATED", ["TRUE"], "")
  783. # Includes
  784. includes = config.get("include_dirs")
  785. if includes:
  786. # This (target include directories) is what requires CMake 2.8.8
  787. includes_name = cmake_target_name + "__include_dirs"
  788. SetVariableList(
  789. output,
  790. includes_name,
  791. [
  792. NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include)
  793. for include in includes
  794. ],
  795. )
  796. output.write("set_property(TARGET ")
  797. output.write(cmake_target_name)
  798. output.write(" APPEND PROPERTY INCLUDE_DIRECTORIES ")
  799. WriteVariable(output, includes_name, "")
  800. output.write(")\n")
  801. # Defines
  802. defines = config.get("defines")
  803. if defines is not None:
  804. SetTargetProperty(
  805. output, cmake_target_name, "COMPILE_DEFINITIONS", defines, ";"
  806. )
  807. # Compile Flags - http://www.cmake.org/Bug/view.php?id=6493
  808. # CMake currently does not have target C and CXX flags.
  809. # So, instead of doing...
  810. # cflags_c = config.get('cflags_c')
  811. # if cflags_c is not None:
  812. # SetTargetProperty(output, cmake_target_name,
  813. # 'C_COMPILE_FLAGS', cflags_c, ' ')
  814. # cflags_cc = config.get('cflags_cc')
  815. # if cflags_cc is not None:
  816. # SetTargetProperty(output, cmake_target_name,
  817. # 'CXX_COMPILE_FLAGS', cflags_cc, ' ')
  818. # Instead we must...
  819. cflags = config.get("cflags", [])
  820. cflags_c = config.get("cflags_c", [])
  821. cflags_cxx = config.get("cflags_cc", [])
  822. if xcode_settings:
  823. cflags = xcode_settings.GetCflags(config_to_use)
  824. cflags_c = xcode_settings.GetCflagsC(config_to_use)
  825. cflags_cxx = xcode_settings.GetCflagsCC(config_to_use)
  826. # cflags_objc = xcode_settings.GetCflagsObjC(config_to_use)
  827. # cflags_objcc = xcode_settings.GetCflagsObjCC(config_to_use)
  828. if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources):
  829. SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", cflags, " ")
  830. elif c_sources and not (s_sources or cxx_sources):
  831. flags = []
  832. flags.extend(cflags)
  833. flags.extend(cflags_c)
  834. SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ")
  835. elif cxx_sources and not (s_sources or c_sources):
  836. flags = []
  837. flags.extend(cflags)
  838. flags.extend(cflags_cxx)
  839. SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ")
  840. else:
  841. # TODO: This is broken, one cannot generally set properties on files,
  842. # as other targets may require different properties on the same files.
  843. if s_sources and cflags:
  844. SetFilesProperty(output, s_sources_name, "COMPILE_FLAGS", cflags, " ")
  845. if c_sources and (cflags or cflags_c):
  846. flags = []
  847. flags.extend(cflags)
  848. flags.extend(cflags_c)
  849. SetFilesProperty(output, c_sources_name, "COMPILE_FLAGS", flags, " ")
  850. if cxx_sources and (cflags or cflags_cxx):
  851. flags = []
  852. flags.extend(cflags)
  853. flags.extend(cflags_cxx)
  854. SetFilesProperty(output, cxx_sources_name, "COMPILE_FLAGS", flags, " ")
  855. # Linker flags
  856. ldflags = config.get("ldflags")
  857. if ldflags is not None:
  858. SetTargetProperty(output, cmake_target_name, "LINK_FLAGS", ldflags, " ")
  859. # XCode settings
  860. xcode_settings = config.get("xcode_settings", {})
  861. for xcode_setting, xcode_value in xcode_settings.items():
  862. SetTargetProperty(
  863. output,
  864. cmake_target_name,
  865. "XCODE_ATTRIBUTE_%s" % xcode_setting,
  866. xcode_value,
  867. "" if isinstance(xcode_value, str) else " ",
  868. )
  869. # Note on Dependencies and Libraries:
  870. # CMake wants to handle link order, resolving the link line up front.
  871. # Gyp does not retain or enforce specifying enough information to do so.
  872. # So do as other gyp generators and use --start-group and --end-group.
  873. # Give CMake as little information as possible so that it doesn't mess it up.
  874. # Dependencies
  875. rawDeps = spec.get("dependencies", [])
  876. static_deps = []
  877. shared_deps = []
  878. other_deps = []
  879. for rawDep in rawDeps:
  880. dep_cmake_name = namer.CreateCMakeTargetName(rawDep)
  881. dep_spec = target_dicts.get(rawDep, {})
  882. dep_target_type = dep_spec.get("type", None)
  883. if dep_target_type == "static_library":
  884. static_deps.append(dep_cmake_name)
  885. elif dep_target_type == "shared_library":
  886. shared_deps.append(dep_cmake_name)
  887. else:
  888. other_deps.append(dep_cmake_name)
  889. # ensure all external dependencies are complete before internal dependencies
  890. # extra_deps currently only depend on their own deps, so otherwise run early
  891. if static_deps or shared_deps or other_deps:
  892. for extra_dep in extra_deps:
  893. output.write("add_dependencies(")
  894. output.write(extra_dep)
  895. output.write("\n")
  896. for deps in (static_deps, shared_deps, other_deps):
  897. for dep in gyp.common.uniquer(deps):
  898. output.write(" ")
  899. output.write(dep)
  900. output.write("\n")
  901. output.write(")\n")
  902. linkable = target_type in ("executable", "loadable_module", "shared_library")
  903. other_deps.extend(extra_deps)
  904. if other_deps or (not linkable and (static_deps or shared_deps)):
  905. output.write("add_dependencies(")
  906. output.write(cmake_target_name)
  907. output.write("\n")
  908. for dep in gyp.common.uniquer(other_deps):
  909. output.write(" ")
  910. output.write(dep)
  911. output.write("\n")
  912. if not linkable:
  913. for deps in (static_deps, shared_deps):
  914. for lib_dep in gyp.common.uniquer(deps):
  915. output.write(" ")
  916. output.write(lib_dep)
  917. output.write("\n")
  918. output.write(")\n")
  919. # Libraries
  920. if linkable:
  921. external_libs = [lib for lib in spec.get("libraries", []) if len(lib) > 0]
  922. if external_libs or static_deps or shared_deps:
  923. output.write("target_link_libraries(")
  924. output.write(cmake_target_name)
  925. output.write("\n")
  926. if static_deps:
  927. write_group = circular_libs and len(static_deps) > 1 and flavor != "mac"
  928. if write_group:
  929. output.write("-Wl,--start-group\n")
  930. for dep in gyp.common.uniquer(static_deps):
  931. output.write(" ")
  932. output.write(dep)
  933. output.write("\n")
  934. if write_group:
  935. output.write("-Wl,--end-group\n")
  936. if shared_deps:
  937. for dep in gyp.common.uniquer(shared_deps):
  938. output.write(" ")
  939. output.write(dep)
  940. output.write("\n")
  941. if external_libs:
  942. for lib in gyp.common.uniquer(external_libs):
  943. output.write(' "')
  944. output.write(RemovePrefix(lib, "$(SDKROOT)"))
  945. output.write('"\n')
  946. output.write(")\n")
  947. UnsetVariable(output, "TOOLSET")
  948. UnsetVariable(output, "TARGET")
  949. def GenerateOutputForConfig(target_list, target_dicts, data, params, config_to_use):
  950. options = params["options"]
  951. generator_flags = params["generator_flags"]
  952. flavor = gyp.common.GetFlavor(params)
  953. # generator_dir: relative path from pwd to where make puts build files.
  954. # Makes migrating from make to cmake easier, cmake doesn't put anything here.
  955. # Each Gyp configuration creates a different CMakeLists.txt file
  956. # to avoid incompatibilities between Gyp and CMake configurations.
  957. generator_dir = os.path.relpath(options.generator_output or ".")
  958. # output_dir: relative path from generator_dir to the build directory.
  959. output_dir = generator_flags.get("output_dir", "out")
  960. # build_dir: relative path from source root to our output files.
  961. # e.g. "out/Debug"
  962. build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_to_use))
  963. toplevel_build = os.path.join(options.toplevel_dir, build_dir)
  964. output_file = os.path.join(toplevel_build, "CMakeLists.txt")
  965. gyp.common.EnsureDirExists(output_file)
  966. output = open(output_file, "w")
  967. output.write("cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n")
  968. output.write("cmake_policy(VERSION 2.8.8)\n")
  969. gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1])
  970. output.write("project(")
  971. output.write(project_target)
  972. output.write(")\n")
  973. SetVariable(output, "configuration", config_to_use)
  974. ar = None
  975. cc = None
  976. cxx = None
  977. make_global_settings = data[gyp_file].get("make_global_settings", [])
  978. build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir)
  979. for key, value in make_global_settings:
  980. if key == "AR":
  981. ar = os.path.join(build_to_top, value)
  982. if key == "CC":
  983. cc = os.path.join(build_to_top, value)
  984. if key == "CXX":
  985. cxx = os.path.join(build_to_top, value)
  986. ar = gyp.common.GetEnvironFallback(["AR_target", "AR"], ar)
  987. cc = gyp.common.GetEnvironFallback(["CC_target", "CC"], cc)
  988. cxx = gyp.common.GetEnvironFallback(["CXX_target", "CXX"], cxx)
  989. if ar:
  990. SetVariable(output, "CMAKE_AR", ar)
  991. if cc:
  992. SetVariable(output, "CMAKE_C_COMPILER", cc)
  993. if cxx:
  994. SetVariable(output, "CMAKE_CXX_COMPILER", cxx)
  995. # The following appears to be as-yet undocumented.
  996. # http://public.kitware.com/Bug/view.php?id=8392
  997. output.write("enable_language(ASM)\n")
  998. # ASM-ATT does not support .S files.
  999. # output.write('enable_language(ASM-ATT)\n')
  1000. if cc:
  1001. SetVariable(output, "CMAKE_ASM_COMPILER", cc)
  1002. SetVariable(output, "builddir", "${CMAKE_CURRENT_BINARY_DIR}")
  1003. SetVariable(output, "obj", "${builddir}/obj")
  1004. output.write("\n")
  1005. # TODO: Undocumented/unsupported (the CMake Java generator depends on it).
  1006. # CMake by default names the object resulting from foo.c to be foo.c.o.
  1007. # Gyp traditionally names the object resulting from foo.c foo.o.
  1008. # This should be irrelevant, but some targets extract .o files from .a
  1009. # and depend on the name of the extracted .o files.
  1010. output.write("set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n")
  1011. output.write("set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n")
  1012. output.write("\n")
  1013. # Force ninja to use rsp files. Otherwise link and ar lines can get too long,
  1014. # resulting in 'Argument list too long' errors.
  1015. # However, rsp files don't work correctly on Mac.
  1016. if flavor != "mac":
  1017. output.write("set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n")
  1018. output.write("\n")
  1019. namer = CMakeNamer(target_list)
  1020. # The list of targets upon which the 'all' target should depend.
  1021. # CMake has it's own implicit 'all' target, one is not created explicitly.
  1022. all_qualified_targets = set()
  1023. for build_file in params["build_files"]:
  1024. for qualified_target in gyp.common.AllTargets(
  1025. target_list, target_dicts, os.path.normpath(build_file)
  1026. ):
  1027. all_qualified_targets.add(qualified_target)
  1028. for qualified_target in target_list:
  1029. if flavor == "mac":
  1030. gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
  1031. spec = target_dicts[qualified_target]
  1032. gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[gyp_file], spec)
  1033. WriteTarget(
  1034. namer,
  1035. qualified_target,
  1036. target_dicts,
  1037. build_dir,
  1038. config_to_use,
  1039. options,
  1040. generator_flags,
  1041. all_qualified_targets,
  1042. flavor,
  1043. output,
  1044. )
  1045. output.close()
  1046. def PerformBuild(data, configurations, params):
  1047. options = params["options"]
  1048. generator_flags = params["generator_flags"]
  1049. # generator_dir: relative path from pwd to where make puts build files.
  1050. # Makes migrating from make to cmake easier, cmake doesn't put anything here.
  1051. generator_dir = os.path.relpath(options.generator_output or ".")
  1052. # output_dir: relative path from generator_dir to the build directory.
  1053. output_dir = generator_flags.get("output_dir", "out")
  1054. for config_name in configurations:
  1055. # build_dir: relative path from source root to our output files.
  1056. # e.g. "out/Debug"
  1057. build_dir = os.path.normpath(
  1058. os.path.join(generator_dir, output_dir, config_name)
  1059. )
  1060. arguments = ["cmake", "-G", "Ninja"]
  1061. print(f"Generating [{config_name}]: {arguments}")
  1062. subprocess.check_call(arguments, cwd=build_dir)
  1063. arguments = ["ninja", "-C", build_dir]
  1064. print(f"Building [{config_name}]: {arguments}")
  1065. subprocess.check_call(arguments)
  1066. def CallGenerateOutputForConfig(arglist):
  1067. # Ignore the interrupt signal so that the parent process catches it and
  1068. # kills all multiprocessing children.
  1069. signal.signal(signal.SIGINT, signal.SIG_IGN)
  1070. target_list, target_dicts, data, params, config_name = arglist
  1071. GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
  1072. def GenerateOutput(target_list, target_dicts, data, params):
  1073. user_config = params.get("generator_flags", {}).get("config", None)
  1074. if user_config:
  1075. GenerateOutputForConfig(target_list, target_dicts, data, params, user_config)
  1076. else:
  1077. config_names = target_dicts[target_list[0]]["configurations"]
  1078. if params["parallel"]:
  1079. try:
  1080. pool = multiprocessing.Pool(len(config_names))
  1081. arglists = []
  1082. for config_name in config_names:
  1083. arglists.append(
  1084. (target_list, target_dicts, data, params, config_name)
  1085. )
  1086. pool.map(CallGenerateOutputForConfig, arglists)
  1087. except KeyboardInterrupt as e:
  1088. pool.terminate()
  1089. raise e
  1090. else:
  1091. for config_name in config_names:
  1092. GenerateOutputForConfig(
  1093. target_list, target_dicts, data, params, config_name
  1094. )