xcode_emulation.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  1. # Copyright (c) 2012 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. """
  5. This module contains classes that help to emulate xcodebuild behavior on top of
  6. other build systems, such as make and ninja.
  7. """
  8. import copy
  9. import gyp.common
  10. import os
  11. import os.path
  12. import re
  13. import shlex
  14. import subprocess
  15. import sys
  16. from gyp.common import GypError
  17. # Populated lazily by XcodeVersion, for efficiency, and to fix an issue when
  18. # "xcodebuild" is called too quickly (it has been found to return incorrect
  19. # version number).
  20. XCODE_VERSION_CACHE = None
  21. # Populated lazily by GetXcodeArchsDefault, to an |XcodeArchsDefault| instance
  22. # corresponding to the installed version of Xcode.
  23. XCODE_ARCHS_DEFAULT_CACHE = None
  24. def XcodeArchsVariableMapping(archs, archs_including_64_bit=None):
  25. """Constructs a dictionary with expansion for $(ARCHS_STANDARD) variable,
  26. and optionally for $(ARCHS_STANDARD_INCLUDING_64_BIT)."""
  27. mapping = {"$(ARCHS_STANDARD)": archs}
  28. if archs_including_64_bit:
  29. mapping["$(ARCHS_STANDARD_INCLUDING_64_BIT)"] = archs_including_64_bit
  30. return mapping
  31. class XcodeArchsDefault:
  32. """A class to resolve ARCHS variable from xcode_settings, resolving Xcode
  33. macros and implementing filtering by VALID_ARCHS. The expansion of macros
  34. depends on the SDKROOT used ("macosx", "iphoneos", "iphonesimulator") and
  35. on the version of Xcode.
  36. """
  37. # Match variable like $(ARCHS_STANDARD).
  38. variable_pattern = re.compile(r"\$\([a-zA-Z_][a-zA-Z0-9_]*\)$")
  39. def __init__(self, default, mac, iphonesimulator, iphoneos):
  40. self._default = (default,)
  41. self._archs = {"mac": mac, "ios": iphoneos, "iossim": iphonesimulator}
  42. def _VariableMapping(self, sdkroot):
  43. """Returns the dictionary of variable mapping depending on the SDKROOT."""
  44. sdkroot = sdkroot.lower()
  45. if "iphoneos" in sdkroot:
  46. return self._archs["ios"]
  47. elif "iphonesimulator" in sdkroot:
  48. return self._archs["iossim"]
  49. else:
  50. return self._archs["mac"]
  51. def _ExpandArchs(self, archs, sdkroot):
  52. """Expands variables references in ARCHS, and remove duplicates."""
  53. variable_mapping = self._VariableMapping(sdkroot)
  54. expanded_archs = []
  55. for arch in archs:
  56. if self.variable_pattern.match(arch):
  57. variable = arch
  58. try:
  59. variable_expansion = variable_mapping[variable]
  60. for arch in variable_expansion:
  61. if arch not in expanded_archs:
  62. expanded_archs.append(arch)
  63. except KeyError:
  64. print('Warning: Ignoring unsupported variable "%s".' % variable)
  65. elif arch not in expanded_archs:
  66. expanded_archs.append(arch)
  67. return expanded_archs
  68. def ActiveArchs(self, archs, valid_archs, sdkroot):
  69. """Expands variables references in ARCHS, and filter by VALID_ARCHS if it
  70. is defined (if not set, Xcode accept any value in ARCHS, otherwise, only
  71. values present in VALID_ARCHS are kept)."""
  72. expanded_archs = self._ExpandArchs(archs or self._default, sdkroot or "")
  73. if valid_archs:
  74. filtered_archs = []
  75. for arch in expanded_archs:
  76. if arch in valid_archs:
  77. filtered_archs.append(arch)
  78. expanded_archs = filtered_archs
  79. return expanded_archs
  80. def GetXcodeArchsDefault():
  81. """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the
  82. installed version of Xcode. The default values used by Xcode for ARCHS
  83. and the expansion of the variables depends on the version of Xcode used.
  84. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included
  85. uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses
  86. $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0
  87. and deprecated with Xcode 5.1.
  88. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit
  89. architecture as part of $(ARCHS_STANDARD) and default to only building it.
  90. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part
  91. of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they
  92. are also part of $(ARCHS_STANDARD).
  93. All these rules are coded in the construction of the |XcodeArchsDefault|
  94. object to use depending on the version of Xcode detected. The object is
  95. for performance reason."""
  96. global XCODE_ARCHS_DEFAULT_CACHE
  97. if XCODE_ARCHS_DEFAULT_CACHE:
  98. return XCODE_ARCHS_DEFAULT_CACHE
  99. xcode_version, _ = XcodeVersion()
  100. if xcode_version < "0500":
  101. XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
  102. "$(ARCHS_STANDARD)",
  103. XcodeArchsVariableMapping(["i386"]),
  104. XcodeArchsVariableMapping(["i386"]),
  105. XcodeArchsVariableMapping(["armv7"]),
  106. )
  107. elif xcode_version < "0510":
  108. XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
  109. "$(ARCHS_STANDARD_INCLUDING_64_BIT)",
  110. XcodeArchsVariableMapping(["x86_64"], ["x86_64"]),
  111. XcodeArchsVariableMapping(["i386"], ["i386", "x86_64"]),
  112. XcodeArchsVariableMapping(
  113. ["armv7", "armv7s"], ["armv7", "armv7s", "arm64"]
  114. ),
  115. )
  116. else:
  117. XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
  118. "$(ARCHS_STANDARD)",
  119. XcodeArchsVariableMapping(["x86_64"], ["x86_64"]),
  120. XcodeArchsVariableMapping(["i386", "x86_64"], ["i386", "x86_64"]),
  121. XcodeArchsVariableMapping(
  122. ["armv7", "armv7s", "arm64"], ["armv7", "armv7s", "arm64"]
  123. ),
  124. )
  125. return XCODE_ARCHS_DEFAULT_CACHE
  126. class XcodeSettings:
  127. """A class that understands the gyp 'xcode_settings' object."""
  128. # Populated lazily by _SdkPath(). Shared by all XcodeSettings, so cached
  129. # at class-level for efficiency.
  130. _sdk_path_cache = {}
  131. _platform_path_cache = {}
  132. _sdk_root_cache = {}
  133. # Populated lazily by GetExtraPlistItems(). Shared by all XcodeSettings, so
  134. # cached at class-level for efficiency.
  135. _plist_cache = {}
  136. # Populated lazily by GetIOSPostbuilds. Shared by all XcodeSettings, so
  137. # cached at class-level for efficiency.
  138. _codesigning_key_cache = {}
  139. def __init__(self, spec):
  140. self.spec = spec
  141. self.isIOS = False
  142. self.mac_toolchain_dir = None
  143. self.header_map_path = None
  144. # Per-target 'xcode_settings' are pushed down into configs earlier by gyp.
  145. # This means self.xcode_settings[config] always contains all settings
  146. # for that config -- the per-target settings as well. Settings that are
  147. # the same for all configs are implicitly per-target settings.
  148. self.xcode_settings = {}
  149. configs = spec["configurations"]
  150. for configname, config in configs.items():
  151. self.xcode_settings[configname] = config.get("xcode_settings", {})
  152. self._ConvertConditionalKeys(configname)
  153. if self.xcode_settings[configname].get("IPHONEOS_DEPLOYMENT_TARGET", None):
  154. self.isIOS = True
  155. # This is only non-None temporarily during the execution of some methods.
  156. self.configname = None
  157. # Used by _AdjustLibrary to match .a and .dylib entries in libraries.
  158. self.library_re = re.compile(r"^lib([^/]+)\.(a|dylib)$")
  159. def _ConvertConditionalKeys(self, configname):
  160. """Converts or warns on conditional keys. Xcode supports conditional keys,
  161. such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation
  162. with some keys converted while the rest force a warning."""
  163. settings = self.xcode_settings[configname]
  164. conditional_keys = [key for key in settings if key.endswith("]")]
  165. for key in conditional_keys:
  166. # If you need more, speak up at http://crbug.com/122592
  167. if key.endswith("[sdk=iphoneos*]"):
  168. if configname.endswith("iphoneos"):
  169. new_key = key.split("[")[0]
  170. settings[new_key] = settings[key]
  171. else:
  172. print(
  173. "Warning: Conditional keys not implemented, ignoring:",
  174. " ".join(conditional_keys),
  175. )
  176. del settings[key]
  177. def _Settings(self):
  178. assert self.configname
  179. return self.xcode_settings[self.configname]
  180. def _Test(self, test_key, cond_key, default):
  181. return self._Settings().get(test_key, default) == cond_key
  182. def _Appendf(self, lst, test_key, format_str, default=None):
  183. if test_key in self._Settings():
  184. lst.append(format_str % str(self._Settings()[test_key]))
  185. elif default:
  186. lst.append(format_str % str(default))
  187. def _WarnUnimplemented(self, test_key):
  188. if test_key in self._Settings():
  189. print('Warning: Ignoring not yet implemented key "%s".' % test_key)
  190. def IsBinaryOutputFormat(self, configname):
  191. default = "binary" if self.isIOS else "xml"
  192. format = self.xcode_settings[configname].get("INFOPLIST_OUTPUT_FORMAT", default)
  193. return format == "binary"
  194. def IsIosFramework(self):
  195. return self.spec["type"] == "shared_library" and self._IsBundle() and self.isIOS
  196. def _IsBundle(self):
  197. return (
  198. int(self.spec.get("mac_bundle", 0)) != 0
  199. or self._IsXCTest()
  200. or self._IsXCUiTest()
  201. )
  202. def _IsXCTest(self):
  203. return int(self.spec.get("mac_xctest_bundle", 0)) != 0
  204. def _IsXCUiTest(self):
  205. return int(self.spec.get("mac_xcuitest_bundle", 0)) != 0
  206. def _IsIosAppExtension(self):
  207. return int(self.spec.get("ios_app_extension", 0)) != 0
  208. def _IsIosWatchKitExtension(self):
  209. return int(self.spec.get("ios_watchkit_extension", 0)) != 0
  210. def _IsIosWatchApp(self):
  211. return int(self.spec.get("ios_watch_app", 0)) != 0
  212. def GetFrameworkVersion(self):
  213. """Returns the framework version of the current target. Only valid for
  214. bundles."""
  215. assert self._IsBundle()
  216. return self.GetPerTargetSetting("FRAMEWORK_VERSION", default="A")
  217. def GetWrapperExtension(self):
  218. """Returns the bundle extension (.app, .framework, .plugin, etc). Only
  219. valid for bundles."""
  220. assert self._IsBundle()
  221. if self.spec["type"] in ("loadable_module", "shared_library"):
  222. default_wrapper_extension = {
  223. "loadable_module": "bundle",
  224. "shared_library": "framework",
  225. }[self.spec["type"]]
  226. wrapper_extension = self.GetPerTargetSetting(
  227. "WRAPPER_EXTENSION", default=default_wrapper_extension
  228. )
  229. return "." + self.spec.get("product_extension", wrapper_extension)
  230. elif self.spec["type"] == "executable":
  231. if self._IsIosAppExtension() or self._IsIosWatchKitExtension():
  232. return "." + self.spec.get("product_extension", "appex")
  233. else:
  234. return "." + self.spec.get("product_extension", "app")
  235. else:
  236. assert False, "Don't know extension for '{}', target '{}'".format(
  237. self.spec["type"],
  238. self.spec["target_name"],
  239. )
  240. def GetProductName(self):
  241. """Returns PRODUCT_NAME."""
  242. return self.spec.get("product_name", self.spec["target_name"])
  243. def GetFullProductName(self):
  244. """Returns FULL_PRODUCT_NAME."""
  245. if self._IsBundle():
  246. return self.GetWrapperName()
  247. else:
  248. return self._GetStandaloneBinaryPath()
  249. def GetWrapperName(self):
  250. """Returns the directory name of the bundle represented by this target.
  251. Only valid for bundles."""
  252. assert self._IsBundle()
  253. return self.GetProductName() + self.GetWrapperExtension()
  254. def GetBundleContentsFolderPath(self):
  255. """Returns the qualified path to the bundle's contents folder. E.g.
  256. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles."""
  257. if self.isIOS:
  258. return self.GetWrapperName()
  259. assert self._IsBundle()
  260. if self.spec["type"] == "shared_library":
  261. return os.path.join(
  262. self.GetWrapperName(), "Versions", self.GetFrameworkVersion()
  263. )
  264. else:
  265. # loadable_modules have a 'Contents' folder like executables.
  266. return os.path.join(self.GetWrapperName(), "Contents")
  267. def GetBundleResourceFolder(self):
  268. """Returns the qualified path to the bundle's resource folder. E.g.
  269. Chromium.app/Contents/Resources. Only valid for bundles."""
  270. assert self._IsBundle()
  271. if self.isIOS:
  272. return self.GetBundleContentsFolderPath()
  273. return os.path.join(self.GetBundleContentsFolderPath(), "Resources")
  274. def GetBundleExecutableFolderPath(self):
  275. """Returns the qualified path to the bundle's executables folder. E.g.
  276. Chromium.app/Contents/MacOS. Only valid for bundles."""
  277. assert self._IsBundle()
  278. if self.spec["type"] in ("shared_library") or self.isIOS:
  279. return self.GetBundleContentsFolderPath()
  280. elif self.spec["type"] in ("executable", "loadable_module"):
  281. return os.path.join(self.GetBundleContentsFolderPath(), "MacOS")
  282. def GetBundleJavaFolderPath(self):
  283. """Returns the qualified path to the bundle's Java resource folder.
  284. E.g. Chromium.app/Contents/Resources/Java. Only valid for bundles."""
  285. assert self._IsBundle()
  286. return os.path.join(self.GetBundleResourceFolder(), "Java")
  287. def GetBundleFrameworksFolderPath(self):
  288. """Returns the qualified path to the bundle's frameworks folder. E.g,
  289. Chromium.app/Contents/Frameworks. Only valid for bundles."""
  290. assert self._IsBundle()
  291. return os.path.join(self.GetBundleContentsFolderPath(), "Frameworks")
  292. def GetBundleSharedFrameworksFolderPath(self):
  293. """Returns the qualified path to the bundle's frameworks folder. E.g,
  294. Chromium.app/Contents/SharedFrameworks. Only valid for bundles."""
  295. assert self._IsBundle()
  296. return os.path.join(self.GetBundleContentsFolderPath(), "SharedFrameworks")
  297. def GetBundleSharedSupportFolderPath(self):
  298. """Returns the qualified path to the bundle's shared support folder. E.g,
  299. Chromium.app/Contents/SharedSupport. Only valid for bundles."""
  300. assert self._IsBundle()
  301. if self.spec["type"] == "shared_library":
  302. return self.GetBundleResourceFolder()
  303. else:
  304. return os.path.join(self.GetBundleContentsFolderPath(), "SharedSupport")
  305. def GetBundlePlugInsFolderPath(self):
  306. """Returns the qualified path to the bundle's plugins folder. E.g,
  307. Chromium.app/Contents/PlugIns. Only valid for bundles."""
  308. assert self._IsBundle()
  309. return os.path.join(self.GetBundleContentsFolderPath(), "PlugIns")
  310. def GetBundleXPCServicesFolderPath(self):
  311. """Returns the qualified path to the bundle's XPC services folder. E.g,
  312. Chromium.app/Contents/XPCServices. Only valid for bundles."""
  313. assert self._IsBundle()
  314. return os.path.join(self.GetBundleContentsFolderPath(), "XPCServices")
  315. def GetBundlePlistPath(self):
  316. """Returns the qualified path to the bundle's plist file. E.g.
  317. Chromium.app/Contents/Info.plist. Only valid for bundles."""
  318. assert self._IsBundle()
  319. if (
  320. self.spec["type"] in ("executable", "loadable_module")
  321. or self.IsIosFramework()
  322. ):
  323. return os.path.join(self.GetBundleContentsFolderPath(), "Info.plist")
  324. else:
  325. return os.path.join(
  326. self.GetBundleContentsFolderPath(), "Resources", "Info.plist"
  327. )
  328. def GetProductType(self):
  329. """Returns the PRODUCT_TYPE of this target."""
  330. if self._IsIosAppExtension():
  331. assert self._IsBundle(), (
  332. "ios_app_extension flag requires mac_bundle "
  333. "(target %s)" % self.spec["target_name"]
  334. )
  335. return "com.apple.product-type.app-extension"
  336. if self._IsIosWatchKitExtension():
  337. assert self._IsBundle(), (
  338. "ios_watchkit_extension flag requires "
  339. "mac_bundle (target %s)" % self.spec["target_name"]
  340. )
  341. return "com.apple.product-type.watchkit-extension"
  342. if self._IsIosWatchApp():
  343. assert self._IsBundle(), (
  344. "ios_watch_app flag requires mac_bundle "
  345. "(target %s)" % self.spec["target_name"]
  346. )
  347. return "com.apple.product-type.application.watchapp"
  348. if self._IsXCUiTest():
  349. assert self._IsBundle(), (
  350. "mac_xcuitest_bundle flag requires mac_bundle "
  351. "(target %s)" % self.spec["target_name"]
  352. )
  353. return "com.apple.product-type.bundle.ui-testing"
  354. if self._IsBundle():
  355. return {
  356. "executable": "com.apple.product-type.application",
  357. "loadable_module": "com.apple.product-type.bundle",
  358. "shared_library": "com.apple.product-type.framework",
  359. }[self.spec["type"]]
  360. else:
  361. return {
  362. "executable": "com.apple.product-type.tool",
  363. "loadable_module": "com.apple.product-type.library.dynamic",
  364. "shared_library": "com.apple.product-type.library.dynamic",
  365. "static_library": "com.apple.product-type.library.static",
  366. }[self.spec["type"]]
  367. def GetMachOType(self):
  368. """Returns the MACH_O_TYPE of this target."""
  369. # Weird, but matches Xcode.
  370. if not self._IsBundle() and self.spec["type"] == "executable":
  371. return ""
  372. return {
  373. "executable": "mh_execute",
  374. "static_library": "staticlib",
  375. "shared_library": "mh_dylib",
  376. "loadable_module": "mh_bundle",
  377. }[self.spec["type"]]
  378. def _GetBundleBinaryPath(self):
  379. """Returns the name of the bundle binary of by this target.
  380. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles."""
  381. assert self._IsBundle()
  382. return os.path.join(
  383. self.GetBundleExecutableFolderPath(), self.GetExecutableName()
  384. )
  385. def _GetStandaloneExecutableSuffix(self):
  386. if "product_extension" in self.spec:
  387. return "." + self.spec["product_extension"]
  388. return {
  389. "executable": "",
  390. "static_library": ".a",
  391. "shared_library": ".dylib",
  392. "loadable_module": ".so",
  393. }[self.spec["type"]]
  394. def _GetStandaloneExecutablePrefix(self):
  395. return self.spec.get(
  396. "product_prefix",
  397. {
  398. "executable": "",
  399. "static_library": "lib",
  400. "shared_library": "lib",
  401. # Non-bundled loadable_modules are called foo.so for some reason
  402. # (that is, .so and no prefix) with the xcode build -- match that.
  403. "loadable_module": "",
  404. }[self.spec["type"]],
  405. )
  406. def _GetStandaloneBinaryPath(self):
  407. """Returns the name of the non-bundle binary represented by this target.
  408. E.g. hello_world. Only valid for non-bundles."""
  409. assert not self._IsBundle()
  410. assert self.spec["type"] in (
  411. "executable",
  412. "shared_library",
  413. "static_library",
  414. "loadable_module",
  415. ), ("Unexpected type %s" % self.spec["type"])
  416. target = self.spec["target_name"]
  417. if self.spec["type"] == "static_library":
  418. if target[:3] == "lib":
  419. target = target[3:]
  420. elif self.spec["type"] in ("loadable_module", "shared_library"):
  421. if target[:3] == "lib":
  422. target = target[3:]
  423. target_prefix = self._GetStandaloneExecutablePrefix()
  424. target = self.spec.get("product_name", target)
  425. target_ext = self._GetStandaloneExecutableSuffix()
  426. return target_prefix + target + target_ext
  427. def GetExecutableName(self):
  428. """Returns the executable name of the bundle represented by this target.
  429. E.g. Chromium."""
  430. if self._IsBundle():
  431. return self.spec.get("product_name", self.spec["target_name"])
  432. else:
  433. return self._GetStandaloneBinaryPath()
  434. def GetExecutablePath(self):
  435. """Returns the qualified path to the primary executable of the bundle
  436. represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium."""
  437. if self._IsBundle():
  438. return self._GetBundleBinaryPath()
  439. else:
  440. return self._GetStandaloneBinaryPath()
  441. def GetActiveArchs(self, configname):
  442. """Returns the architectures this target should be built for."""
  443. config_settings = self.xcode_settings[configname]
  444. xcode_archs_default = GetXcodeArchsDefault()
  445. return xcode_archs_default.ActiveArchs(
  446. config_settings.get("ARCHS"),
  447. config_settings.get("VALID_ARCHS"),
  448. config_settings.get("SDKROOT"),
  449. )
  450. def _GetSdkVersionInfoItem(self, sdk, infoitem):
  451. # xcodebuild requires Xcode and can't run on Command Line Tools-only
  452. # systems from 10.7 onward.
  453. # Since the CLT has no SDK paths anyway, returning None is the
  454. # most sensible route and should still do the right thing.
  455. try:
  456. return GetStdoutQuiet(["xcrun", "--sdk", sdk, infoitem])
  457. except GypError:
  458. pass
  459. def _SdkRoot(self, configname):
  460. if configname is None:
  461. configname = self.configname
  462. return self.GetPerConfigSetting("SDKROOT", configname, default="")
  463. def _XcodePlatformPath(self, configname=None):
  464. sdk_root = self._SdkRoot(configname)
  465. if sdk_root not in XcodeSettings._platform_path_cache:
  466. platform_path = self._GetSdkVersionInfoItem(
  467. sdk_root, "--show-sdk-platform-path"
  468. )
  469. XcodeSettings._platform_path_cache[sdk_root] = platform_path
  470. return XcodeSettings._platform_path_cache[sdk_root]
  471. def _SdkPath(self, configname=None):
  472. sdk_root = self._SdkRoot(configname)
  473. if sdk_root.startswith("/"):
  474. return sdk_root
  475. return self._XcodeSdkPath(sdk_root)
  476. def _XcodeSdkPath(self, sdk_root):
  477. if sdk_root not in XcodeSettings._sdk_path_cache:
  478. sdk_path = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-path")
  479. XcodeSettings._sdk_path_cache[sdk_root] = sdk_path
  480. if sdk_root:
  481. XcodeSettings._sdk_root_cache[sdk_path] = sdk_root
  482. return XcodeSettings._sdk_path_cache[sdk_root]
  483. def _AppendPlatformVersionMinFlags(self, lst):
  484. self._Appendf(lst, "MACOSX_DEPLOYMENT_TARGET", "-mmacosx-version-min=%s")
  485. if "IPHONEOS_DEPLOYMENT_TARGET" in self._Settings():
  486. # TODO: Implement this better?
  487. sdk_path_basename = os.path.basename(self._SdkPath())
  488. if sdk_path_basename.lower().startswith("iphonesimulator"):
  489. self._Appendf(
  490. lst, "IPHONEOS_DEPLOYMENT_TARGET", "-mios-simulator-version-min=%s"
  491. )
  492. else:
  493. self._Appendf(
  494. lst, "IPHONEOS_DEPLOYMENT_TARGET", "-miphoneos-version-min=%s"
  495. )
  496. def GetCflags(self, configname, arch=None):
  497. """Returns flags that need to be added to .c, .cc, .m, and .mm
  498. compilations."""
  499. # This functions (and the similar ones below) do not offer complete
  500. # emulation of all xcode_settings keys. They're implemented on demand.
  501. self.configname = configname
  502. cflags = []
  503. sdk_root = self._SdkPath()
  504. if "SDKROOT" in self._Settings() and sdk_root:
  505. cflags.append("-isysroot %s" % sdk_root)
  506. if self.header_map_path:
  507. cflags.append("-I%s" % self.header_map_path)
  508. if self._Test("CLANG_WARN_CONSTANT_CONVERSION", "YES", default="NO"):
  509. cflags.append("-Wconstant-conversion")
  510. if self._Test("GCC_CHAR_IS_UNSIGNED_CHAR", "YES", default="NO"):
  511. cflags.append("-funsigned-char")
  512. if self._Test("GCC_CW_ASM_SYNTAX", "YES", default="YES"):
  513. cflags.append("-fasm-blocks")
  514. if "GCC_DYNAMIC_NO_PIC" in self._Settings():
  515. if self._Settings()["GCC_DYNAMIC_NO_PIC"] == "YES":
  516. cflags.append("-mdynamic-no-pic")
  517. else:
  518. pass
  519. # TODO: In this case, it depends on the target. xcode passes
  520. # mdynamic-no-pic by default for executable and possibly static lib
  521. # according to mento
  522. if self._Test("GCC_ENABLE_PASCAL_STRINGS", "YES", default="YES"):
  523. cflags.append("-mpascal-strings")
  524. self._Appendf(cflags, "GCC_OPTIMIZATION_LEVEL", "-O%s", default="s")
  525. if self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES"):
  526. dbg_format = self._Settings().get("DEBUG_INFORMATION_FORMAT", "dwarf")
  527. if dbg_format == "dwarf":
  528. cflags.append("-gdwarf-2")
  529. elif dbg_format == "stabs":
  530. raise NotImplementedError("stabs debug format is not supported yet.")
  531. elif dbg_format == "dwarf-with-dsym":
  532. cflags.append("-gdwarf-2")
  533. else:
  534. raise NotImplementedError("Unknown debug format %s" % dbg_format)
  535. if self._Settings().get("GCC_STRICT_ALIASING") == "YES":
  536. cflags.append("-fstrict-aliasing")
  537. elif self._Settings().get("GCC_STRICT_ALIASING") == "NO":
  538. cflags.append("-fno-strict-aliasing")
  539. if self._Test("GCC_SYMBOLS_PRIVATE_EXTERN", "YES", default="NO"):
  540. cflags.append("-fvisibility=hidden")
  541. if self._Test("GCC_TREAT_WARNINGS_AS_ERRORS", "YES", default="NO"):
  542. cflags.append("-Werror")
  543. if self._Test("GCC_WARN_ABOUT_MISSING_NEWLINE", "YES", default="NO"):
  544. cflags.append("-Wnewline-eof")
  545. # In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or
  546. # llvm-gcc. It also requires a fairly recent libtool, and
  547. # if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the
  548. # path to the libLTO.dylib that matches the used clang.
  549. if self._Test("LLVM_LTO", "YES", default="NO"):
  550. cflags.append("-flto")
  551. self._AppendPlatformVersionMinFlags(cflags)
  552. # TODO:
  553. if self._Test("COPY_PHASE_STRIP", "YES", default="NO"):
  554. self._WarnUnimplemented("COPY_PHASE_STRIP")
  555. self._WarnUnimplemented("GCC_DEBUGGING_SYMBOLS")
  556. self._WarnUnimplemented("GCC_ENABLE_OBJC_EXCEPTIONS")
  557. # TODO: This is exported correctly, but assigning to it is not supported.
  558. self._WarnUnimplemented("MACH_O_TYPE")
  559. self._WarnUnimplemented("PRODUCT_TYPE")
  560. # If GYP_CROSSCOMPILE (--cross-compiling), disable architecture-specific
  561. # additions and assume these will be provided as required via CC_host,
  562. # CXX_host, CC_target and CXX_target.
  563. if not gyp.common.CrossCompileRequested():
  564. if arch is not None:
  565. archs = [arch]
  566. else:
  567. assert self.configname
  568. archs = self.GetActiveArchs(self.configname)
  569. if len(archs) != 1:
  570. # TODO: Supporting fat binaries will be annoying.
  571. self._WarnUnimplemented("ARCHS")
  572. archs = ["i386"]
  573. cflags.append("-arch " + archs[0])
  574. if archs[0] in ("i386", "x86_64"):
  575. if self._Test("GCC_ENABLE_SSE3_EXTENSIONS", "YES", default="NO"):
  576. cflags.append("-msse3")
  577. if self._Test(
  578. "GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS", "YES", default="NO"
  579. ):
  580. cflags.append("-mssse3") # Note 3rd 's'.
  581. if self._Test("GCC_ENABLE_SSE41_EXTENSIONS", "YES", default="NO"):
  582. cflags.append("-msse4.1")
  583. if self._Test("GCC_ENABLE_SSE42_EXTENSIONS", "YES", default="NO"):
  584. cflags.append("-msse4.2")
  585. cflags += self._Settings().get("WARNING_CFLAGS", [])
  586. if self._IsXCTest():
  587. platform_root = self._XcodePlatformPath(configname)
  588. if platform_root:
  589. cflags.append("-F" + platform_root + "/Developer/Library/Frameworks/")
  590. if sdk_root:
  591. framework_root = sdk_root
  592. else:
  593. framework_root = ""
  594. config = self.spec["configurations"][self.configname]
  595. framework_dirs = config.get("mac_framework_dirs", [])
  596. for directory in framework_dirs:
  597. cflags.append("-F" + directory.replace("$(SDKROOT)", framework_root))
  598. self.configname = None
  599. return cflags
  600. def GetCflagsC(self, configname):
  601. """Returns flags that need to be added to .c, and .m compilations."""
  602. self.configname = configname
  603. cflags_c = []
  604. if self._Settings().get("GCC_C_LANGUAGE_STANDARD", "") == "ansi":
  605. cflags_c.append("-ansi")
  606. else:
  607. self._Appendf(cflags_c, "GCC_C_LANGUAGE_STANDARD", "-std=%s")
  608. cflags_c += self._Settings().get("OTHER_CFLAGS", [])
  609. self.configname = None
  610. return cflags_c
  611. def GetCflagsCC(self, configname):
  612. """Returns flags that need to be added to .cc, and .mm compilations."""
  613. self.configname = configname
  614. cflags_cc = []
  615. clang_cxx_language_standard = self._Settings().get(
  616. "CLANG_CXX_LANGUAGE_STANDARD"
  617. )
  618. # Note: Don't make c++0x to c++11 so that c++0x can be used with older
  619. # clangs that don't understand c++11 yet (like Xcode 4.2's).
  620. if clang_cxx_language_standard:
  621. cflags_cc.append("-std=%s" % clang_cxx_language_standard)
  622. self._Appendf(cflags_cc, "CLANG_CXX_LIBRARY", "-stdlib=%s")
  623. if self._Test("GCC_ENABLE_CPP_RTTI", "NO", default="YES"):
  624. cflags_cc.append("-fno-rtti")
  625. if self._Test("GCC_ENABLE_CPP_EXCEPTIONS", "NO", default="YES"):
  626. cflags_cc.append("-fno-exceptions")
  627. if self._Test("GCC_INLINES_ARE_PRIVATE_EXTERN", "YES", default="NO"):
  628. cflags_cc.append("-fvisibility-inlines-hidden")
  629. if self._Test("GCC_THREADSAFE_STATICS", "NO", default="YES"):
  630. cflags_cc.append("-fno-threadsafe-statics")
  631. # Note: This flag is a no-op for clang, it only has an effect for gcc.
  632. if self._Test("GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO", "NO", default="YES"):
  633. cflags_cc.append("-Wno-invalid-offsetof")
  634. other_ccflags = []
  635. for flag in self._Settings().get("OTHER_CPLUSPLUSFLAGS", ["$(inherited)"]):
  636. # TODO: More general variable expansion. Missing in many other places too.
  637. if flag in ("$inherited", "$(inherited)", "${inherited}"):
  638. flag = "$OTHER_CFLAGS"
  639. if flag in ("$OTHER_CFLAGS", "$(OTHER_CFLAGS)", "${OTHER_CFLAGS}"):
  640. other_ccflags += self._Settings().get("OTHER_CFLAGS", [])
  641. else:
  642. other_ccflags.append(flag)
  643. cflags_cc += other_ccflags
  644. self.configname = None
  645. return cflags_cc
  646. def _AddObjectiveCGarbageCollectionFlags(self, flags):
  647. gc_policy = self._Settings().get("GCC_ENABLE_OBJC_GC", "unsupported")
  648. if gc_policy == "supported":
  649. flags.append("-fobjc-gc")
  650. elif gc_policy == "required":
  651. flags.append("-fobjc-gc-only")
  652. def _AddObjectiveCARCFlags(self, flags):
  653. if self._Test("CLANG_ENABLE_OBJC_ARC", "YES", default="NO"):
  654. flags.append("-fobjc-arc")
  655. def _AddObjectiveCMissingPropertySynthesisFlags(self, flags):
  656. if self._Test(
  657. "CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS", "YES", default="NO"
  658. ):
  659. flags.append("-Wobjc-missing-property-synthesis")
  660. def GetCflagsObjC(self, configname):
  661. """Returns flags that need to be added to .m compilations."""
  662. self.configname = configname
  663. cflags_objc = []
  664. self._AddObjectiveCGarbageCollectionFlags(cflags_objc)
  665. self._AddObjectiveCARCFlags(cflags_objc)
  666. self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc)
  667. self.configname = None
  668. return cflags_objc
  669. def GetCflagsObjCC(self, configname):
  670. """Returns flags that need to be added to .mm compilations."""
  671. self.configname = configname
  672. cflags_objcc = []
  673. self._AddObjectiveCGarbageCollectionFlags(cflags_objcc)
  674. self._AddObjectiveCARCFlags(cflags_objcc)
  675. self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc)
  676. if self._Test("GCC_OBJC_CALL_CXX_CDTORS", "YES", default="NO"):
  677. cflags_objcc.append("-fobjc-call-cxx-cdtors")
  678. self.configname = None
  679. return cflags_objcc
  680. def GetInstallNameBase(self):
  681. """Return DYLIB_INSTALL_NAME_BASE for this target."""
  682. # Xcode sets this for shared_libraries, and for nonbundled loadable_modules.
  683. if self.spec["type"] != "shared_library" and (
  684. self.spec["type"] != "loadable_module" or self._IsBundle()
  685. ):
  686. return None
  687. install_base = self.GetPerTargetSetting(
  688. "DYLIB_INSTALL_NAME_BASE",
  689. default="/Library/Frameworks" if self._IsBundle() else "/usr/local/lib",
  690. )
  691. return install_base
  692. def _StandardizePath(self, path):
  693. """Do :standardizepath processing for path."""
  694. # I'm not quite sure what :standardizepath does. Just call normpath(),
  695. # but don't let @executable_path/../foo collapse to foo.
  696. if "/" in path:
  697. prefix, rest = "", path
  698. if path.startswith("@"):
  699. prefix, rest = path.split("/", 1)
  700. rest = os.path.normpath(rest) # :standardizepath
  701. path = os.path.join(prefix, rest)
  702. return path
  703. def GetInstallName(self):
  704. """Return LD_DYLIB_INSTALL_NAME for this target."""
  705. # Xcode sets this for shared_libraries, and for nonbundled loadable_modules.
  706. if self.spec["type"] != "shared_library" and (
  707. self.spec["type"] != "loadable_module" or self._IsBundle()
  708. ):
  709. return None
  710. default_install_name = (
  711. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)"
  712. )
  713. install_name = self.GetPerTargetSetting(
  714. "LD_DYLIB_INSTALL_NAME", default=default_install_name
  715. )
  716. # Hardcode support for the variables used in chromium for now, to
  717. # unblock people using the make build.
  718. if "$" in install_name:
  719. assert install_name in (
  720. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/"
  721. "$(WRAPPER_NAME)/$(PRODUCT_NAME)",
  722. default_install_name,
  723. ), (
  724. "Variables in LD_DYLIB_INSTALL_NAME are not generally supported "
  725. "yet in target '%s' (got '%s')"
  726. % (self.spec["target_name"], install_name)
  727. )
  728. install_name = install_name.replace(
  729. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)",
  730. self._StandardizePath(self.GetInstallNameBase()),
  731. )
  732. if self._IsBundle():
  733. # These are only valid for bundles, hence the |if|.
  734. install_name = install_name.replace(
  735. "$(WRAPPER_NAME)", self.GetWrapperName()
  736. )
  737. install_name = install_name.replace(
  738. "$(PRODUCT_NAME)", self.GetProductName()
  739. )
  740. else:
  741. assert "$(WRAPPER_NAME)" not in install_name
  742. assert "$(PRODUCT_NAME)" not in install_name
  743. install_name = install_name.replace(
  744. "$(EXECUTABLE_PATH)", self.GetExecutablePath()
  745. )
  746. return install_name
  747. def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path):
  748. """Checks if ldflag contains a filename and if so remaps it from
  749. gyp-directory-relative to build-directory-relative."""
  750. # This list is expanded on demand.
  751. # They get matched as:
  752. # -exported_symbols_list file
  753. # -Wl,exported_symbols_list file
  754. # -Wl,exported_symbols_list,file
  755. LINKER_FILE = r"(\S+)"
  756. WORD = r"\S+"
  757. linker_flags = [
  758. ["-exported_symbols_list", LINKER_FILE], # Needed for NaCl.
  759. ["-unexported_symbols_list", LINKER_FILE],
  760. ["-reexported_symbols_list", LINKER_FILE],
  761. ["-sectcreate", WORD, WORD, LINKER_FILE], # Needed for remoting.
  762. ]
  763. for flag_pattern in linker_flags:
  764. regex = re.compile("(?:-Wl,)?" + "[ ,]".join(flag_pattern))
  765. m = regex.match(ldflag)
  766. if m:
  767. ldflag = (
  768. ldflag[: m.start(1)]
  769. + gyp_to_build_path(m.group(1))
  770. + ldflag[m.end(1) :]
  771. )
  772. # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS,
  773. # TODO(thakis): Update ffmpeg.gyp):
  774. if ldflag.startswith("-L"):
  775. ldflag = "-L" + gyp_to_build_path(ldflag[len("-L") :])
  776. return ldflag
  777. def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
  778. """Returns flags that need to be passed to the linker.
  779. Args:
  780. configname: The name of the configuration to get ld flags for.
  781. product_dir: The directory where products such static and dynamic
  782. libraries are placed. This is added to the library search path.
  783. gyp_to_build_path: A function that converts paths relative to the
  784. current gyp file to paths relative to the build directory.
  785. """
  786. self.configname = configname
  787. ldflags = []
  788. # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS
  789. # can contain entries that depend on this. Explicitly absolutify these.
  790. for ldflag in self._Settings().get("OTHER_LDFLAGS", []):
  791. ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path))
  792. if self._Test("DEAD_CODE_STRIPPING", "YES", default="NO"):
  793. ldflags.append("-Wl,-dead_strip")
  794. if self._Test("PREBINDING", "YES", default="NO"):
  795. ldflags.append("-Wl,-prebind")
  796. self._Appendf(
  797. ldflags, "DYLIB_COMPATIBILITY_VERSION", "-compatibility_version %s"
  798. )
  799. self._Appendf(ldflags, "DYLIB_CURRENT_VERSION", "-current_version %s")
  800. self._AppendPlatformVersionMinFlags(ldflags)
  801. if "SDKROOT" in self._Settings() and self._SdkPath():
  802. ldflags.append("-isysroot " + self._SdkPath())
  803. for library_path in self._Settings().get("LIBRARY_SEARCH_PATHS", []):
  804. ldflags.append("-L" + gyp_to_build_path(library_path))
  805. if "ORDER_FILE" in self._Settings():
  806. ldflags.append(
  807. "-Wl,-order_file "
  808. + "-Wl,"
  809. + gyp_to_build_path(self._Settings()["ORDER_FILE"])
  810. )
  811. if not gyp.common.CrossCompileRequested():
  812. if arch is not None:
  813. archs = [arch]
  814. else:
  815. assert self.configname
  816. archs = self.GetActiveArchs(self.configname)
  817. if len(archs) != 1:
  818. # TODO: Supporting fat binaries will be annoying.
  819. self._WarnUnimplemented("ARCHS")
  820. archs = ["i386"]
  821. ldflags.append("-arch " + archs[0])
  822. # Xcode adds the product directory by default.
  823. # Rewrite -L. to -L./ to work around http://www.openradar.me/25313838
  824. ldflags.append("-L" + (product_dir if product_dir != "." else "./"))
  825. install_name = self.GetInstallName()
  826. if install_name and self.spec["type"] != "loadable_module":
  827. ldflags.append("-install_name " + install_name.replace(" ", r"\ "))
  828. for rpath in self._Settings().get("LD_RUNPATH_SEARCH_PATHS", []):
  829. ldflags.append("-Wl,-rpath," + rpath)
  830. sdk_root = self._SdkPath()
  831. if not sdk_root:
  832. sdk_root = ""
  833. config = self.spec["configurations"][self.configname]
  834. framework_dirs = config.get("mac_framework_dirs", [])
  835. for directory in framework_dirs:
  836. ldflags.append("-F" + directory.replace("$(SDKROOT)", sdk_root))
  837. if self._IsXCTest():
  838. platform_root = self._XcodePlatformPath(configname)
  839. if sdk_root and platform_root:
  840. ldflags.append("-F" + platform_root + "/Developer/Library/Frameworks/")
  841. ldflags.append("-framework XCTest")
  842. is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension()
  843. if sdk_root and is_extension:
  844. # Adds the link flags for extensions. These flags are common for all
  845. # extensions and provide loader and main function.
  846. # These flags reflect the compilation options used by xcode to compile
  847. # extensions.
  848. xcode_version, _ = XcodeVersion()
  849. if xcode_version < "0900":
  850. ldflags.append("-lpkstart")
  851. ldflags.append(
  852. sdk_root
  853. + "/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit"
  854. )
  855. else:
  856. ldflags.append("-e _NSExtensionMain")
  857. ldflags.append("-fapplication-extension")
  858. self._Appendf(ldflags, "CLANG_CXX_LIBRARY", "-stdlib=%s")
  859. self.configname = None
  860. return ldflags
  861. def GetLibtoolflags(self, configname):
  862. """Returns flags that need to be passed to the static linker.
  863. Args:
  864. configname: The name of the configuration to get ld flags for.
  865. """
  866. self.configname = configname
  867. libtoolflags = []
  868. for libtoolflag in self._Settings().get("OTHER_LDFLAGS", []):
  869. libtoolflags.append(libtoolflag)
  870. # TODO(thakis): ARCHS?
  871. self.configname = None
  872. return libtoolflags
  873. def GetPerTargetSettings(self):
  874. """Gets a list of all the per-target settings. This will only fetch keys
  875. whose values are the same across all configurations."""
  876. first_pass = True
  877. result = {}
  878. for configname in sorted(self.xcode_settings.keys()):
  879. if first_pass:
  880. result = dict(self.xcode_settings[configname])
  881. first_pass = False
  882. else:
  883. for key, value in self.xcode_settings[configname].items():
  884. if key not in result:
  885. continue
  886. elif result[key] != value:
  887. del result[key]
  888. return result
  889. def GetPerConfigSetting(self, setting, configname, default=None):
  890. if configname in self.xcode_settings:
  891. return self.xcode_settings[configname].get(setting, default)
  892. else:
  893. return self.GetPerTargetSetting(setting, default)
  894. def GetPerTargetSetting(self, setting, default=None):
  895. """Tries to get xcode_settings.setting from spec. Assumes that the setting
  896. has the same value in all configurations and throws otherwise."""
  897. is_first_pass = True
  898. result = None
  899. for configname in sorted(self.xcode_settings.keys()):
  900. if is_first_pass:
  901. result = self.xcode_settings[configname].get(setting, None)
  902. is_first_pass = False
  903. else:
  904. assert result == self.xcode_settings[configname].get(setting, None), (
  905. "Expected per-target setting for '%s', got per-config setting "
  906. "(target %s)" % (setting, self.spec["target_name"])
  907. )
  908. if result is None:
  909. return default
  910. return result
  911. def _GetStripPostbuilds(self, configname, output_binary, quiet):
  912. """Returns a list of shell commands that contain the shell commands
  913. necessary to strip this target's binary. These should be run as postbuilds
  914. before the actual postbuilds run."""
  915. self.configname = configname
  916. result = []
  917. if self._Test("DEPLOYMENT_POSTPROCESSING", "YES", default="NO") and self._Test(
  918. "STRIP_INSTALLED_PRODUCT", "YES", default="NO"
  919. ):
  920. default_strip_style = "debugging"
  921. if (
  922. self.spec["type"] == "loadable_module" or self._IsIosAppExtension()
  923. ) and self._IsBundle():
  924. default_strip_style = "non-global"
  925. elif self.spec["type"] == "executable":
  926. default_strip_style = "all"
  927. strip_style = self._Settings().get("STRIP_STYLE", default_strip_style)
  928. strip_flags = {"all": "", "non-global": "-x", "debugging": "-S"}[
  929. strip_style
  930. ]
  931. explicit_strip_flags = self._Settings().get("STRIPFLAGS", "")
  932. if explicit_strip_flags:
  933. strip_flags += " " + _NormalizeEnvVarReferences(explicit_strip_flags)
  934. if not quiet:
  935. result.append("echo STRIP\\(%s\\)" % self.spec["target_name"])
  936. result.append(f"strip {strip_flags} {output_binary}")
  937. self.configname = None
  938. return result
  939. def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet):
  940. """Returns a list of shell commands that contain the shell commands
  941. necessary to massage this target's debug information. These should be run
  942. as postbuilds before the actual postbuilds run."""
  943. self.configname = configname
  944. # For static libraries, no dSYMs are created.
  945. result = []
  946. if (
  947. self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES")
  948. and self._Test(
  949. "DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym", default="dwarf"
  950. )
  951. and self.spec["type"] != "static_library"
  952. ):
  953. if not quiet:
  954. result.append("echo DSYMUTIL\\(%s\\)" % self.spec["target_name"])
  955. result.append("dsymutil {} -o {}".format(output_binary, output + ".dSYM"))
  956. self.configname = None
  957. return result
  958. def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False):
  959. """Returns a list of shell commands that contain the shell commands
  960. to run as postbuilds for this target, before the actual postbuilds."""
  961. # dSYMs need to build before stripping happens.
  962. return self._GetDebugInfoPostbuilds(
  963. configname, output, output_binary, quiet
  964. ) + self._GetStripPostbuilds(configname, output_binary, quiet)
  965. def _GetIOSPostbuilds(self, configname, output_binary):
  966. """Return a shell command to codesign the iOS output binary so it can
  967. be deployed to a device. This should be run as the very last step of the
  968. build."""
  969. if not (
  970. self.isIOS
  971. and (self.spec["type"] == "executable" or self._IsXCTest())
  972. or self.IsIosFramework()
  973. ):
  974. return []
  975. postbuilds = []
  976. product_name = self.GetFullProductName()
  977. settings = self.xcode_settings[configname]
  978. # Xcode expects XCTests to be copied into the TEST_HOST dir.
  979. if self._IsXCTest():
  980. source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name)
  981. test_host = os.path.dirname(settings.get("TEST_HOST"))
  982. xctest_destination = os.path.join(test_host, "PlugIns", product_name)
  983. postbuilds.extend([f"ditto {source} {xctest_destination}"])
  984. key = self._GetIOSCodeSignIdentityKey(settings)
  985. if not key:
  986. return postbuilds
  987. # Warn for any unimplemented signing xcode keys.
  988. unimpl = ["OTHER_CODE_SIGN_FLAGS"]
  989. unimpl = set(unimpl) & set(self.xcode_settings[configname].keys())
  990. if unimpl:
  991. print(
  992. "Warning: Some codesign keys not implemented, ignoring: %s"
  993. % ", ".join(sorted(unimpl))
  994. )
  995. if self._IsXCTest():
  996. # For device xctests, Xcode copies two extra frameworks into $TEST_HOST.
  997. test_host = os.path.dirname(settings.get("TEST_HOST"))
  998. frameworks_dir = os.path.join(test_host, "Frameworks")
  999. platform_root = self._XcodePlatformPath(configname)
  1000. frameworks = [
  1001. "Developer/Library/PrivateFrameworks/IDEBundleInjection.framework",
  1002. "Developer/Library/Frameworks/XCTest.framework",
  1003. ]
  1004. for framework in frameworks:
  1005. source = os.path.join(platform_root, framework)
  1006. destination = os.path.join(frameworks_dir, os.path.basename(framework))
  1007. postbuilds.extend([f"ditto {source} {destination}"])
  1008. # Then re-sign everything with 'preserve=True'
  1009. postbuilds.extend(
  1010. [
  1011. '%s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1012. % (
  1013. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1014. key,
  1015. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1016. settings.get("PROVISIONING_PROFILE", ""),
  1017. destination,
  1018. True,
  1019. )
  1020. ]
  1021. )
  1022. plugin_dir = os.path.join(test_host, "PlugIns")
  1023. targets = [os.path.join(plugin_dir, product_name), test_host]
  1024. for target in targets:
  1025. postbuilds.extend(
  1026. [
  1027. '%s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1028. % (
  1029. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1030. key,
  1031. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1032. settings.get("PROVISIONING_PROFILE", ""),
  1033. target,
  1034. True,
  1035. )
  1036. ]
  1037. )
  1038. postbuilds.extend(
  1039. [
  1040. '%s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1041. % (
  1042. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1043. key,
  1044. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1045. settings.get("PROVISIONING_PROFILE", ""),
  1046. os.path.join("${BUILT_PRODUCTS_DIR}", product_name),
  1047. False,
  1048. )
  1049. ]
  1050. )
  1051. return postbuilds
  1052. def _GetIOSCodeSignIdentityKey(self, settings):
  1053. identity = settings.get("CODE_SIGN_IDENTITY")
  1054. if not identity:
  1055. return None
  1056. if identity not in XcodeSettings._codesigning_key_cache:
  1057. output = subprocess.check_output(
  1058. ["security", "find-identity", "-p", "codesigning", "-v"]
  1059. )
  1060. for line in output.splitlines():
  1061. if identity in line:
  1062. fingerprint = line.split()[1]
  1063. cache = XcodeSettings._codesigning_key_cache
  1064. assert identity not in cache or fingerprint == cache[identity], (
  1065. "Multiple codesigning fingerprints for identity: %s" % identity
  1066. )
  1067. XcodeSettings._codesigning_key_cache[identity] = fingerprint
  1068. return XcodeSettings._codesigning_key_cache.get(identity, "")
  1069. def AddImplicitPostbuilds(
  1070. self, configname, output, output_binary, postbuilds=[], quiet=False
  1071. ):
  1072. """Returns a list of shell commands that should run before and after
  1073. |postbuilds|."""
  1074. assert output_binary is not None
  1075. pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet)
  1076. post = self._GetIOSPostbuilds(configname, output_binary)
  1077. return pre + postbuilds + post
  1078. def _AdjustLibrary(self, library, config_name=None):
  1079. if library.endswith(".framework"):
  1080. l_flag = "-framework " + os.path.splitext(os.path.basename(library))[0]
  1081. else:
  1082. m = self.library_re.match(library)
  1083. if m:
  1084. l_flag = "-l" + m.group(1)
  1085. else:
  1086. l_flag = library
  1087. sdk_root = self._SdkPath(config_name)
  1088. if not sdk_root:
  1089. sdk_root = ""
  1090. # Xcode 7 started shipping with ".tbd" (text based stubs) files instead of
  1091. # ".dylib" without providing a real support for them. What it does, for
  1092. # "/usr/lib" libraries, is do "-L/usr/lib -lname" which is dependent on the
  1093. # library order and cause collision when building Chrome.
  1094. #
  1095. # Instead substitute ".tbd" to ".dylib" in the generated project when the
  1096. # following conditions are both true:
  1097. # - library is referenced in the gyp file as "$(SDKROOT)/**/*.dylib",
  1098. # - the ".dylib" file does not exists but a ".tbd" file do.
  1099. library = l_flag.replace("$(SDKROOT)", sdk_root)
  1100. if l_flag.startswith("$(SDKROOT)"):
  1101. basename, ext = os.path.splitext(library)
  1102. if ext == ".dylib" and not os.path.exists(library):
  1103. tbd_library = basename + ".tbd"
  1104. if os.path.exists(tbd_library):
  1105. library = tbd_library
  1106. return library
  1107. def AdjustLibraries(self, libraries, config_name=None):
  1108. """Transforms entries like 'Cocoa.framework' in libraries into entries like
  1109. '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
  1110. """
  1111. libraries = [self._AdjustLibrary(library, config_name) for library in libraries]
  1112. return libraries
  1113. def _BuildMachineOSBuild(self):
  1114. return GetStdout(["sw_vers", "-buildVersion"])
  1115. def _XcodeIOSDeviceFamily(self, configname):
  1116. family = self.xcode_settings[configname].get("TARGETED_DEVICE_FAMILY", "1")
  1117. return [int(x) for x in family.split(",")]
  1118. def GetExtraPlistItems(self, configname=None):
  1119. """Returns a dictionary with extra items to insert into Info.plist."""
  1120. if configname not in XcodeSettings._plist_cache:
  1121. cache = {}
  1122. cache["BuildMachineOSBuild"] = self._BuildMachineOSBuild()
  1123. xcode_version, xcode_build = XcodeVersion()
  1124. cache["DTXcode"] = xcode_version
  1125. cache["DTXcodeBuild"] = xcode_build
  1126. compiler = self.xcode_settings[configname].get("GCC_VERSION")
  1127. if compiler is not None:
  1128. cache["DTCompiler"] = compiler
  1129. sdk_root = self._SdkRoot(configname)
  1130. if not sdk_root:
  1131. sdk_root = self._DefaultSdkRoot()
  1132. sdk_version = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-version")
  1133. cache["DTSDKName"] = sdk_root + (sdk_version or "")
  1134. if xcode_version >= "0720":
  1135. cache["DTSDKBuild"] = self._GetSdkVersionInfoItem(
  1136. sdk_root, "--show-sdk-build-version"
  1137. )
  1138. elif xcode_version >= "0430":
  1139. cache["DTSDKBuild"] = sdk_version
  1140. else:
  1141. cache["DTSDKBuild"] = cache["BuildMachineOSBuild"]
  1142. if self.isIOS:
  1143. cache["MinimumOSVersion"] = self.xcode_settings[configname].get(
  1144. "IPHONEOS_DEPLOYMENT_TARGET"
  1145. )
  1146. cache["DTPlatformName"] = sdk_root
  1147. cache["DTPlatformVersion"] = sdk_version
  1148. if configname.endswith("iphoneos"):
  1149. cache["CFBundleSupportedPlatforms"] = ["iPhoneOS"]
  1150. cache["DTPlatformBuild"] = cache["DTSDKBuild"]
  1151. else:
  1152. cache["CFBundleSupportedPlatforms"] = ["iPhoneSimulator"]
  1153. # This is weird, but Xcode sets DTPlatformBuild to an empty field
  1154. # for simulator builds.
  1155. cache["DTPlatformBuild"] = ""
  1156. XcodeSettings._plist_cache[configname] = cache
  1157. # Include extra plist items that are per-target, not per global
  1158. # XcodeSettings.
  1159. items = dict(XcodeSettings._plist_cache[configname])
  1160. if self.isIOS:
  1161. items["UIDeviceFamily"] = self._XcodeIOSDeviceFamily(configname)
  1162. return items
  1163. def _DefaultSdkRoot(self):
  1164. """Returns the default SDKROOT to use.
  1165. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode
  1166. project, then the environment variable was empty. Starting with this
  1167. version, Xcode uses the name of the newest SDK installed.
  1168. """
  1169. xcode_version, _ = XcodeVersion()
  1170. if xcode_version < "0500":
  1171. return ""
  1172. default_sdk_path = self._XcodeSdkPath("")
  1173. default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path)
  1174. if default_sdk_root:
  1175. return default_sdk_root
  1176. try:
  1177. all_sdks = GetStdout(["xcodebuild", "-showsdks"])
  1178. except GypError:
  1179. # If xcodebuild fails, there will be no valid SDKs
  1180. return ""
  1181. for line in all_sdks.splitlines():
  1182. items = line.split()
  1183. if len(items) >= 3 and items[-2] == "-sdk":
  1184. sdk_root = items[-1]
  1185. sdk_path = self._XcodeSdkPath(sdk_root)
  1186. if sdk_path == default_sdk_path:
  1187. return sdk_root
  1188. return ""
  1189. class MacPrefixHeader:
  1190. """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature.
  1191. This feature consists of several pieces:
  1192. * If GCC_PREFIX_HEADER is present, all compilations in that project get an
  1193. additional |-include path_to_prefix_header| cflag.
  1194. * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is
  1195. instead compiled, and all other compilations in the project get an
  1196. additional |-include path_to_compiled_header| instead.
  1197. + Compiled prefix headers have the extension gch. There is one gch file for
  1198. every language used in the project (c, cc, m, mm), since gch files for
  1199. different languages aren't compatible.
  1200. + gch files themselves are built with the target's normal cflags, but they
  1201. obviously don't get the |-include| flag. Instead, they need a -x flag that
  1202. describes their language.
  1203. + All o files in the target need to depend on the gch file, to make sure
  1204. it's built before any o file is built.
  1205. This class helps with some of these tasks, but it needs help from the build
  1206. system for writing dependencies to the gch files, for writing build commands
  1207. for the gch files, and for figuring out the location of the gch files.
  1208. """
  1209. def __init__(
  1210. self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output
  1211. ):
  1212. """If xcode_settings is None, all methods on this class are no-ops.
  1213. Args:
  1214. gyp_path_to_build_path: A function that takes a gyp-relative path,
  1215. and returns a path relative to the build directory.
  1216. gyp_path_to_build_output: A function that takes a gyp-relative path and
  1217. a language code ('c', 'cc', 'm', or 'mm'), and that returns a path
  1218. to where the output of precompiling that path for that language
  1219. should be placed (without the trailing '.gch').
  1220. """
  1221. # This doesn't support per-configuration prefix headers. Good enough
  1222. # for now.
  1223. self.header = None
  1224. self.compile_headers = False
  1225. if xcode_settings:
  1226. self.header = xcode_settings.GetPerTargetSetting("GCC_PREFIX_HEADER")
  1227. self.compile_headers = (
  1228. xcode_settings.GetPerTargetSetting(
  1229. "GCC_PRECOMPILE_PREFIX_HEADER", default="NO"
  1230. )
  1231. != "NO"
  1232. )
  1233. self.compiled_headers = {}
  1234. if self.header:
  1235. if self.compile_headers:
  1236. for lang in ["c", "cc", "m", "mm"]:
  1237. self.compiled_headers[lang] = gyp_path_to_build_output(
  1238. self.header, lang
  1239. )
  1240. self.header = gyp_path_to_build_path(self.header)
  1241. def _CompiledHeader(self, lang, arch):
  1242. assert self.compile_headers
  1243. h = self.compiled_headers[lang]
  1244. if arch:
  1245. h += "." + arch
  1246. return h
  1247. def GetInclude(self, lang, arch=None):
  1248. """Gets the cflags to include the prefix header for language |lang|."""
  1249. if self.compile_headers and lang in self.compiled_headers:
  1250. return "-include %s" % self._CompiledHeader(lang, arch)
  1251. elif self.header:
  1252. return "-include %s" % self.header
  1253. else:
  1254. return ""
  1255. def _Gch(self, lang, arch):
  1256. """Returns the actual file name of the prefix header for language |lang|."""
  1257. assert self.compile_headers
  1258. return self._CompiledHeader(lang, arch) + ".gch"
  1259. def GetObjDependencies(self, sources, objs, arch=None):
  1260. """Given a list of source files and the corresponding object files, returns
  1261. a list of (source, object, gch) tuples, where |gch| is the build-directory
  1262. relative path to the gch file each object file depends on. |compilable[i]|
  1263. has to be the source file belonging to |objs[i]|."""
  1264. if not self.header or not self.compile_headers:
  1265. return []
  1266. result = []
  1267. for source, obj in zip(sources, objs):
  1268. ext = os.path.splitext(source)[1]
  1269. lang = {
  1270. ".c": "c",
  1271. ".cpp": "cc",
  1272. ".cc": "cc",
  1273. ".cxx": "cc",
  1274. ".m": "m",
  1275. ".mm": "mm",
  1276. }.get(ext, None)
  1277. if lang:
  1278. result.append((source, obj, self._Gch(lang, arch)))
  1279. return result
  1280. def GetPchBuildCommands(self, arch=None):
  1281. """Returns [(path_to_gch, language_flag, language, header)].
  1282. |path_to_gch| and |header| are relative to the build directory.
  1283. """
  1284. if not self.header or not self.compile_headers:
  1285. return []
  1286. return [
  1287. (self._Gch("c", arch), "-x c-header", "c", self.header),
  1288. (self._Gch("cc", arch), "-x c++-header", "cc", self.header),
  1289. (self._Gch("m", arch), "-x objective-c-header", "m", self.header),
  1290. (self._Gch("mm", arch), "-x objective-c++-header", "mm", self.header),
  1291. ]
  1292. def XcodeVersion():
  1293. """Returns a tuple of version and build version of installed Xcode."""
  1294. # `xcodebuild -version` output looks like
  1295. # Xcode 4.6.3
  1296. # Build version 4H1503
  1297. # or like
  1298. # Xcode 3.2.6
  1299. # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0
  1300. # BuildVersion: 10M2518
  1301. # Convert that to ('0463', '4H1503') or ('0326', '10M2518').
  1302. global XCODE_VERSION_CACHE
  1303. if XCODE_VERSION_CACHE:
  1304. return XCODE_VERSION_CACHE
  1305. version = ""
  1306. build = ""
  1307. try:
  1308. version_list = GetStdoutQuiet(["xcodebuild", "-version"]).splitlines()
  1309. # In some circumstances xcodebuild exits 0 but doesn't return
  1310. # the right results; for example, a user on 10.7 or 10.8 with
  1311. # a bogus path set via xcode-select
  1312. # In that case this may be a CLT-only install so fall back to
  1313. # checking that version.
  1314. if len(version_list) < 2:
  1315. raise GypError("xcodebuild returned unexpected results")
  1316. version = version_list[0].split()[-1] # Last word on first line
  1317. build = version_list[-1].split()[-1] # Last word on last line
  1318. except GypError: # Xcode not installed so look for XCode Command Line Tools
  1319. version = CLTVersion() # macOS Catalina returns 11.0.0.0.1.1567737322
  1320. if not version:
  1321. raise GypError("No Xcode or CLT version detected!")
  1322. # Be careful to convert "4.2.3" to "0423" and "11.0.0" to "1100":
  1323. version = version.split(".")[:3] # Just major, minor, micro
  1324. version[0] = version[0].zfill(2) # Add a leading zero if major is one digit
  1325. version = ("".join(version) + "00")[:4] # Limit to exactly four characters
  1326. XCODE_VERSION_CACHE = (version, build)
  1327. return XCODE_VERSION_CACHE
  1328. # This function ported from the logic in Homebrew's CLT version check
  1329. def CLTVersion():
  1330. """Returns the version of command-line tools from pkgutil."""
  1331. # pkgutil output looks like
  1332. # package-id: com.apple.pkg.CLTools_Executables
  1333. # version: 5.0.1.0.1.1382131676
  1334. # volume: /
  1335. # location: /
  1336. # install-time: 1382544035
  1337. # groups: com.apple.FindSystemFiles.pkg-group
  1338. # com.apple.DevToolsBoth.pkg-group
  1339. # com.apple.DevToolsNonRelocatableShared.pkg-group
  1340. STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo"
  1341. FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI"
  1342. MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables"
  1343. regex = re.compile("version: (?P<version>.+)")
  1344. for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]:
  1345. try:
  1346. output = GetStdout(["/usr/sbin/pkgutil", "--pkg-info", key])
  1347. return re.search(regex, output).groupdict()["version"]
  1348. except GypError:
  1349. continue
  1350. regex = re.compile(r'Command Line Tools for Xcode\s+(?P<version>\S+)')
  1351. try:
  1352. output = GetStdout(["/usr/sbin/softwareupdate", "--history"])
  1353. return re.search(regex, output).groupdict()["version"]
  1354. except GypError:
  1355. return None
  1356. def GetStdoutQuiet(cmdlist):
  1357. """Returns the content of standard output returned by invoking |cmdlist|.
  1358. Ignores the stderr.
  1359. Raises |GypError| if the command return with a non-zero return code."""
  1360. job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1361. out = job.communicate()[0].decode("utf-8")
  1362. if job.returncode != 0:
  1363. raise GypError("Error %d running %s" % (job.returncode, cmdlist[0]))
  1364. return out.rstrip("\n")
  1365. def GetStdout(cmdlist):
  1366. """Returns the content of standard output returned by invoking |cmdlist|.
  1367. Raises |GypError| if the command return with a non-zero return code."""
  1368. job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE)
  1369. out = job.communicate()[0].decode("utf-8")
  1370. if job.returncode != 0:
  1371. sys.stderr.write(out + "\n")
  1372. raise GypError("Error %d running %s" % (job.returncode, cmdlist[0]))
  1373. return out.rstrip("\n")
  1374. def MergeGlobalXcodeSettingsToSpec(global_dict, spec):
  1375. """Merges the global xcode_settings dictionary into each configuration of the
  1376. target represented by spec. For keys that are both in the global and the local
  1377. xcode_settings dict, the local key gets precedence.
  1378. """
  1379. # The xcode generator special-cases global xcode_settings and does something
  1380. # that amounts to merging in the global xcode_settings into each local
  1381. # xcode_settings dict.
  1382. global_xcode_settings = global_dict.get("xcode_settings", {})
  1383. for config in spec["configurations"].values():
  1384. if "xcode_settings" in config:
  1385. new_settings = global_xcode_settings.copy()
  1386. new_settings.update(config["xcode_settings"])
  1387. config["xcode_settings"] = new_settings
  1388. def IsMacBundle(flavor, spec):
  1389. """Returns if |spec| should be treated as a bundle.
  1390. Bundles are directories with a certain subdirectory structure, instead of
  1391. just a single file. Bundle rules do not produce a binary but also package
  1392. resources into that directory."""
  1393. is_mac_bundle = (
  1394. int(spec.get("mac_xctest_bundle", 0)) != 0
  1395. or int(spec.get("mac_xcuitest_bundle", 0)) != 0
  1396. or (int(spec.get("mac_bundle", 0)) != 0 and flavor == "mac")
  1397. )
  1398. if is_mac_bundle:
  1399. assert spec["type"] != "none", (
  1400. 'mac_bundle targets cannot have type none (target "%s")'
  1401. % spec["target_name"]
  1402. )
  1403. return is_mac_bundle
  1404. def GetMacBundleResources(product_dir, xcode_settings, resources):
  1405. """Yields (output, resource) pairs for every resource in |resources|.
  1406. Only call this for mac bundle targets.
  1407. Args:
  1408. product_dir: Path to the directory containing the output bundle,
  1409. relative to the build directory.
  1410. xcode_settings: The XcodeSettings of the current target.
  1411. resources: A list of bundle resources, relative to the build directory.
  1412. """
  1413. dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder())
  1414. for res in resources:
  1415. output = dest
  1416. # The make generator doesn't support it, so forbid it everywhere
  1417. # to keep the generators more interchangeable.
  1418. assert " " not in res, "Spaces in resource filenames not supported (%s)" % res
  1419. # Split into (path,file).
  1420. res_parts = os.path.split(res)
  1421. # Now split the path into (prefix,maybe.lproj).
  1422. lproj_parts = os.path.split(res_parts[0])
  1423. # If the resource lives in a .lproj bundle, add that to the destination.
  1424. if lproj_parts[1].endswith(".lproj"):
  1425. output = os.path.join(output, lproj_parts[1])
  1426. output = os.path.join(output, res_parts[1])
  1427. # Compiled XIB files are referred to by .nib.
  1428. if output.endswith(".xib"):
  1429. output = os.path.splitext(output)[0] + ".nib"
  1430. # Compiled storyboard files are referred to by .storyboardc.
  1431. if output.endswith(".storyboard"):
  1432. output = os.path.splitext(output)[0] + ".storyboardc"
  1433. yield output, res
  1434. def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path):
  1435. """Returns (info_plist, dest_plist, defines, extra_env), where:
  1436. * |info_plist| is the source plist path, relative to the
  1437. build directory,
  1438. * |dest_plist| is the destination plist path, relative to the
  1439. build directory,
  1440. * |defines| is a list of preprocessor defines (empty if the plist
  1441. shouldn't be preprocessed,
  1442. * |extra_env| is a dict of env variables that should be exported when
  1443. invoking |mac_tool copy-info-plist|.
  1444. Only call this for mac bundle targets.
  1445. Args:
  1446. product_dir: Path to the directory containing the output bundle,
  1447. relative to the build directory.
  1448. xcode_settings: The XcodeSettings of the current target.
  1449. gyp_to_build_path: A function that converts paths relative to the
  1450. current gyp file to paths relative to the build directory.
  1451. """
  1452. info_plist = xcode_settings.GetPerTargetSetting("INFOPLIST_FILE")
  1453. if not info_plist:
  1454. return None, None, [], {}
  1455. # The make generator doesn't support it, so forbid it everywhere
  1456. # to keep the generators more interchangeable.
  1457. assert " " not in info_plist, (
  1458. "Spaces in Info.plist filenames not supported (%s)" % info_plist
  1459. )
  1460. info_plist = gyp_path_to_build_path(info_plist)
  1461. # If explicitly set to preprocess the plist, invoke the C preprocessor and
  1462. # specify any defines as -D flags.
  1463. if (
  1464. xcode_settings.GetPerTargetSetting("INFOPLIST_PREPROCESS", default="NO")
  1465. == "YES"
  1466. ):
  1467. # Create an intermediate file based on the path.
  1468. defines = shlex.split(
  1469. xcode_settings.GetPerTargetSetting(
  1470. "INFOPLIST_PREPROCESSOR_DEFINITIONS", default=""
  1471. )
  1472. )
  1473. else:
  1474. defines = []
  1475. dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath())
  1476. extra_env = xcode_settings.GetPerTargetSettings()
  1477. return info_plist, dest_plist, defines, extra_env
  1478. def _GetXcodeEnv(
  1479. xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None
  1480. ):
  1481. """Return the environment variables that Xcode would set. See
  1482. http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153
  1483. for a full list.
  1484. Args:
  1485. xcode_settings: An XcodeSettings object. If this is None, this function
  1486. returns an empty dict.
  1487. built_products_dir: Absolute path to the built products dir.
  1488. srcroot: Absolute path to the source root.
  1489. configuration: The build configuration name.
  1490. additional_settings: An optional dict with more values to add to the
  1491. result.
  1492. """
  1493. if not xcode_settings:
  1494. return {}
  1495. # This function is considered a friend of XcodeSettings, so let it reach into
  1496. # its implementation details.
  1497. spec = xcode_settings.spec
  1498. # These are filled in on an as-needed basis.
  1499. env = {
  1500. "BUILT_FRAMEWORKS_DIR": built_products_dir,
  1501. "BUILT_PRODUCTS_DIR": built_products_dir,
  1502. "CONFIGURATION": configuration,
  1503. "PRODUCT_NAME": xcode_settings.GetProductName(),
  1504. # For FULL_PRODUCT_NAME see:
  1505. # /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec # noqa: E501
  1506. "SRCROOT": srcroot,
  1507. "SOURCE_ROOT": "${SRCROOT}",
  1508. # This is not true for static libraries, but currently the env is only
  1509. # written for bundles:
  1510. "TARGET_BUILD_DIR": built_products_dir,
  1511. "TEMP_DIR": "${TMPDIR}",
  1512. "XCODE_VERSION_ACTUAL": XcodeVersion()[0],
  1513. }
  1514. if xcode_settings.GetPerConfigSetting("SDKROOT", configuration):
  1515. env["SDKROOT"] = xcode_settings._SdkPath(configuration)
  1516. else:
  1517. env["SDKROOT"] = ""
  1518. if xcode_settings.mac_toolchain_dir:
  1519. env["DEVELOPER_DIR"] = xcode_settings.mac_toolchain_dir
  1520. if spec["type"] in (
  1521. "executable",
  1522. "static_library",
  1523. "shared_library",
  1524. "loadable_module",
  1525. ):
  1526. env["EXECUTABLE_NAME"] = xcode_settings.GetExecutableName()
  1527. env["EXECUTABLE_PATH"] = xcode_settings.GetExecutablePath()
  1528. env["FULL_PRODUCT_NAME"] = xcode_settings.GetFullProductName()
  1529. mach_o_type = xcode_settings.GetMachOType()
  1530. if mach_o_type:
  1531. env["MACH_O_TYPE"] = mach_o_type
  1532. env["PRODUCT_TYPE"] = xcode_settings.GetProductType()
  1533. if xcode_settings._IsBundle():
  1534. # xcodeproj_file.py sets the same Xcode subfolder value for this as for
  1535. # FRAMEWORKS_FOLDER_PATH so Xcode builds will actually use FFP's value.
  1536. env["BUILT_FRAMEWORKS_DIR"] = os.path.join(
  1537. built_products_dir + os.sep + xcode_settings.GetBundleFrameworksFolderPath()
  1538. )
  1539. env["CONTENTS_FOLDER_PATH"] = xcode_settings.GetBundleContentsFolderPath()
  1540. env["EXECUTABLE_FOLDER_PATH"] = xcode_settings.GetBundleExecutableFolderPath()
  1541. env[
  1542. "UNLOCALIZED_RESOURCES_FOLDER_PATH"
  1543. ] = xcode_settings.GetBundleResourceFolder()
  1544. env["JAVA_FOLDER_PATH"] = xcode_settings.GetBundleJavaFolderPath()
  1545. env["FRAMEWORKS_FOLDER_PATH"] = xcode_settings.GetBundleFrameworksFolderPath()
  1546. env[
  1547. "SHARED_FRAMEWORKS_FOLDER_PATH"
  1548. ] = xcode_settings.GetBundleSharedFrameworksFolderPath()
  1549. env[
  1550. "SHARED_SUPPORT_FOLDER_PATH"
  1551. ] = xcode_settings.GetBundleSharedSupportFolderPath()
  1552. env["PLUGINS_FOLDER_PATH"] = xcode_settings.GetBundlePlugInsFolderPath()
  1553. env["XPCSERVICES_FOLDER_PATH"] = xcode_settings.GetBundleXPCServicesFolderPath()
  1554. env["INFOPLIST_PATH"] = xcode_settings.GetBundlePlistPath()
  1555. env["WRAPPER_NAME"] = xcode_settings.GetWrapperName()
  1556. install_name = xcode_settings.GetInstallName()
  1557. if install_name:
  1558. env["LD_DYLIB_INSTALL_NAME"] = install_name
  1559. install_name_base = xcode_settings.GetInstallNameBase()
  1560. if install_name_base:
  1561. env["DYLIB_INSTALL_NAME_BASE"] = install_name_base
  1562. xcode_version, _ = XcodeVersion()
  1563. if xcode_version >= "0500" and not env.get("SDKROOT"):
  1564. sdk_root = xcode_settings._SdkRoot(configuration)
  1565. if not sdk_root:
  1566. sdk_root = xcode_settings._XcodeSdkPath("")
  1567. if sdk_root is None:
  1568. sdk_root = ""
  1569. env["SDKROOT"] = sdk_root
  1570. if not additional_settings:
  1571. additional_settings = {}
  1572. else:
  1573. # Flatten lists to strings.
  1574. for k in additional_settings:
  1575. if not isinstance(additional_settings[k], str):
  1576. additional_settings[k] = " ".join(additional_settings[k])
  1577. additional_settings.update(env)
  1578. for k in additional_settings:
  1579. additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k])
  1580. return additional_settings
  1581. def _NormalizeEnvVarReferences(str):
  1582. """Takes a string containing variable references in the form ${FOO}, $(FOO),
  1583. or $FOO, and returns a string with all variable references in the form ${FOO}.
  1584. """
  1585. # $FOO -> ${FOO}
  1586. str = re.sub(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", r"${\1}", str)
  1587. # $(FOO) -> ${FOO}
  1588. matches = re.findall(r"(\$\(([a-zA-Z0-9\-_]+)\))", str)
  1589. for match in matches:
  1590. to_replace, variable = match
  1591. assert "$(" not in match, "$($(FOO)) variables not supported: " + match
  1592. str = str.replace(to_replace, "${" + variable + "}")
  1593. return str
  1594. def ExpandEnvVars(string, expansions):
  1595. """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the
  1596. expansions list. If the variable expands to something that references
  1597. another variable, this variable is expanded as well if it's in env --
  1598. until no variables present in env are left."""
  1599. for k, v in reversed(expansions):
  1600. string = string.replace("${" + k + "}", v)
  1601. string = string.replace("$(" + k + ")", v)
  1602. string = string.replace("$" + k, v)
  1603. return string
  1604. def _TopologicallySortedEnvVarKeys(env):
  1605. """Takes a dict |env| whose values are strings that can refer to other keys,
  1606. for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of
  1607. env such that key2 is after key1 in L if env[key2] refers to env[key1].
  1608. Throws an Exception in case of dependency cycles.
  1609. """
  1610. # Since environment variables can refer to other variables, the evaluation
  1611. # order is important. Below is the logic to compute the dependency graph
  1612. # and sort it.
  1613. regex = re.compile(r"\$\{([a-zA-Z0-9\-_]+)\}")
  1614. def GetEdges(node):
  1615. # Use a definition of edges such that user_of_variable -> used_varible.
  1616. # This happens to be easier in this case, since a variable's
  1617. # definition contains all variables it references in a single string.
  1618. # We can then reverse the result of the topological sort at the end.
  1619. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
  1620. matches = {v for v in regex.findall(env[node]) if v in env}
  1621. for dependee in matches:
  1622. assert "${" not in dependee, "Nested variables not supported: " + dependee
  1623. return matches
  1624. try:
  1625. # Topologically sort, and then reverse, because we used an edge definition
  1626. # that's inverted from the expected result of this function (see comment
  1627. # above).
  1628. order = gyp.common.TopologicallySorted(env.keys(), GetEdges)
  1629. order.reverse()
  1630. return order
  1631. except gyp.common.CycleError as e:
  1632. raise GypError(
  1633. "Xcode environment variables are cyclically dependent: " + str(e.nodes)
  1634. )
  1635. def GetSortedXcodeEnv(
  1636. xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None
  1637. ):
  1638. env = _GetXcodeEnv(
  1639. xcode_settings, built_products_dir, srcroot, configuration, additional_settings
  1640. )
  1641. return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)]
  1642. def GetSpecPostbuildCommands(spec, quiet=False):
  1643. """Returns the list of postbuilds explicitly defined on |spec|, in a form
  1644. executable by a shell."""
  1645. postbuilds = []
  1646. for postbuild in spec.get("postbuilds", []):
  1647. if not quiet:
  1648. postbuilds.append(
  1649. "echo POSTBUILD\\(%s\\) %s"
  1650. % (spec["target_name"], postbuild["postbuild_name"])
  1651. )
  1652. postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild["action"]))
  1653. return postbuilds
  1654. def _HasIOSTarget(targets):
  1655. """Returns true if any target contains the iOS specific key
  1656. IPHONEOS_DEPLOYMENT_TARGET."""
  1657. for target_dict in targets.values():
  1658. for config in target_dict["configurations"].values():
  1659. if config.get("xcode_settings", {}).get("IPHONEOS_DEPLOYMENT_TARGET"):
  1660. return True
  1661. return False
  1662. def _AddIOSDeviceConfigurations(targets):
  1663. """Clone all targets and append -iphoneos to the name. Configure these targets
  1664. to build for iOS devices and use correct architectures for those builds."""
  1665. for target_dict in targets.values():
  1666. toolset = target_dict["toolset"]
  1667. configs = target_dict["configurations"]
  1668. for config_name, simulator_config_dict in dict(configs).items():
  1669. iphoneos_config_dict = copy.deepcopy(simulator_config_dict)
  1670. configs[config_name + "-iphoneos"] = iphoneos_config_dict
  1671. configs[config_name + "-iphonesimulator"] = simulator_config_dict
  1672. if toolset == "target":
  1673. simulator_config_dict["xcode_settings"]["SDKROOT"] = "iphonesimulator"
  1674. iphoneos_config_dict["xcode_settings"]["SDKROOT"] = "iphoneos"
  1675. return targets
  1676. def CloneConfigurationForDeviceAndEmulator(target_dicts):
  1677. """If |target_dicts| contains any iOS targets, automatically create -iphoneos
  1678. targets for iOS device builds."""
  1679. if _HasIOSTarget(target_dicts):
  1680. return _AddIOSDeviceConfigurations(target_dicts)
  1681. return target_dicts