f0759030f3949bb7a0873c15d70ef60f222af9fd97c4c78d231c95c4a1c3ac0cd99e24298076c23e40c15c2db0a17383a0411751307277fda922f3618accca 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  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")
  506. cflags.append(sdk_root)
  507. if self.header_map_path:
  508. cflags.append("-I%s" % self.header_map_path)
  509. if self._Test("CLANG_WARN_CONSTANT_CONVERSION", "YES", default="NO"):
  510. cflags.append("-Wconstant-conversion")
  511. if self._Test("GCC_CHAR_IS_UNSIGNED_CHAR", "YES", default="NO"):
  512. cflags.append("-funsigned-char")
  513. if self._Test("GCC_CW_ASM_SYNTAX", "YES", default="YES"):
  514. cflags.append("-fasm-blocks")
  515. if "GCC_DYNAMIC_NO_PIC" in self._Settings():
  516. if self._Settings()["GCC_DYNAMIC_NO_PIC"] == "YES":
  517. cflags.append("-mdynamic-no-pic")
  518. else:
  519. pass
  520. # TODO: In this case, it depends on the target. xcode passes
  521. # mdynamic-no-pic by default for executable and possibly static lib
  522. # according to mento
  523. if self._Test("GCC_ENABLE_PASCAL_STRINGS", "YES", default="YES"):
  524. cflags.append("-mpascal-strings")
  525. self._Appendf(cflags, "GCC_OPTIMIZATION_LEVEL", "-O%s", default="s")
  526. if self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES"):
  527. dbg_format = self._Settings().get("DEBUG_INFORMATION_FORMAT", "dwarf")
  528. if dbg_format == "dwarf":
  529. cflags.append("-gdwarf-2")
  530. elif dbg_format == "stabs":
  531. raise NotImplementedError("stabs debug format is not supported yet.")
  532. elif dbg_format == "dwarf-with-dsym":
  533. cflags.append("-gdwarf-2")
  534. else:
  535. raise NotImplementedError("Unknown debug format %s" % dbg_format)
  536. if self._Settings().get("GCC_STRICT_ALIASING") == "YES":
  537. cflags.append("-fstrict-aliasing")
  538. elif self._Settings().get("GCC_STRICT_ALIASING") == "NO":
  539. cflags.append("-fno-strict-aliasing")
  540. if self._Test("GCC_SYMBOLS_PRIVATE_EXTERN", "YES", default="NO"):
  541. cflags.append("-fvisibility=hidden")
  542. if self._Test("GCC_TREAT_WARNINGS_AS_ERRORS", "YES", default="NO"):
  543. cflags.append("-Werror")
  544. if self._Test("GCC_WARN_ABOUT_MISSING_NEWLINE", "YES", default="NO"):
  545. cflags.append("-Wnewline-eof")
  546. # In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or
  547. # llvm-gcc. It also requires a fairly recent libtool, and
  548. # if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the
  549. # path to the libLTO.dylib that matches the used clang.
  550. if self._Test("LLVM_LTO", "YES", default="NO"):
  551. cflags.append("-flto")
  552. self._AppendPlatformVersionMinFlags(cflags)
  553. # TODO:
  554. if self._Test("COPY_PHASE_STRIP", "YES", default="NO"):
  555. self._WarnUnimplemented("COPY_PHASE_STRIP")
  556. self._WarnUnimplemented("GCC_DEBUGGING_SYMBOLS")
  557. self._WarnUnimplemented("GCC_ENABLE_OBJC_EXCEPTIONS")
  558. # TODO: This is exported correctly, but assigning to it is not supported.
  559. self._WarnUnimplemented("MACH_O_TYPE")
  560. self._WarnUnimplemented("PRODUCT_TYPE")
  561. # If GYP_CROSSCOMPILE (--cross-compiling), disable architecture-specific
  562. # additions and assume these will be provided as required via CC_host,
  563. # CXX_host, CC_target and CXX_target.
  564. if not gyp.common.CrossCompileRequested():
  565. if arch is not None:
  566. archs = [arch]
  567. else:
  568. assert self.configname
  569. archs = self.GetActiveArchs(self.configname)
  570. if len(archs) != 1:
  571. # TODO: Supporting fat binaries will be annoying.
  572. self._WarnUnimplemented("ARCHS")
  573. archs = ["i386"]
  574. cflags.append("-arch")
  575. cflags.append(archs[0])
  576. if archs[0] in ("i386", "x86_64"):
  577. if self._Test("GCC_ENABLE_SSE3_EXTENSIONS", "YES", default="NO"):
  578. cflags.append("-msse3")
  579. if self._Test(
  580. "GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS", "YES", default="NO"
  581. ):
  582. cflags.append("-mssse3") # Note 3rd 's'.
  583. if self._Test("GCC_ENABLE_SSE41_EXTENSIONS", "YES", default="NO"):
  584. cflags.append("-msse4.1")
  585. if self._Test("GCC_ENABLE_SSE42_EXTENSIONS", "YES", default="NO"):
  586. cflags.append("-msse4.2")
  587. cflags += self._Settings().get("WARNING_CFLAGS", [])
  588. if self._IsXCTest():
  589. platform_root = self._XcodePlatformPath(configname)
  590. if platform_root:
  591. cflags.append("-F" + platform_root + "/Developer/Library/Frameworks/")
  592. framework_root = sdk_root if sdk_root else ""
  593. config = self.spec["configurations"][self.configname]
  594. framework_dirs = config.get("mac_framework_dirs", [])
  595. for directory in framework_dirs:
  596. cflags.append("-F" + directory.replace("$(SDKROOT)", framework_root))
  597. self.configname = None
  598. return cflags
  599. def GetCflagsC(self, configname):
  600. """Returns flags that need to be added to .c, and .m compilations."""
  601. self.configname = configname
  602. cflags_c = []
  603. if self._Settings().get("GCC_C_LANGUAGE_STANDARD", "") == "ansi":
  604. cflags_c.append("-ansi")
  605. else:
  606. self._Appendf(cflags_c, "GCC_C_LANGUAGE_STANDARD", "-std=%s")
  607. cflags_c += self._Settings().get("OTHER_CFLAGS", [])
  608. self.configname = None
  609. return cflags_c
  610. def GetCflagsCC(self, configname):
  611. """Returns flags that need to be added to .cc, and .mm compilations."""
  612. self.configname = configname
  613. cflags_cc = []
  614. clang_cxx_language_standard = self._Settings().get(
  615. "CLANG_CXX_LANGUAGE_STANDARD"
  616. )
  617. # Note: Don't make c++0x to c++11 so that c++0x can be used with older
  618. # clangs that don't understand c++11 yet (like Xcode 4.2's).
  619. if clang_cxx_language_standard:
  620. cflags_cc.append("-std=%s" % clang_cxx_language_standard)
  621. self._Appendf(cflags_cc, "CLANG_CXX_LIBRARY", "-stdlib=%s")
  622. if self._Test("GCC_ENABLE_CPP_RTTI", "NO", default="YES"):
  623. cflags_cc.append("-fno-rtti")
  624. if self._Test("GCC_ENABLE_CPP_EXCEPTIONS", "NO", default="YES"):
  625. cflags_cc.append("-fno-exceptions")
  626. if self._Test("GCC_INLINES_ARE_PRIVATE_EXTERN", "YES", default="NO"):
  627. cflags_cc.append("-fvisibility-inlines-hidden")
  628. if self._Test("GCC_THREADSAFE_STATICS", "NO", default="YES"):
  629. cflags_cc.append("-fno-threadsafe-statics")
  630. # Note: This flag is a no-op for clang, it only has an effect for gcc.
  631. if self._Test("GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO", "NO", default="YES"):
  632. cflags_cc.append("-Wno-invalid-offsetof")
  633. other_ccflags = []
  634. for flag in self._Settings().get("OTHER_CPLUSPLUSFLAGS", ["$(inherited)"]):
  635. # TODO: More general variable expansion. Missing in many other places too.
  636. if flag in ("$inherited", "$(inherited)", "${inherited}"):
  637. flag = "$OTHER_CFLAGS"
  638. if flag in ("$OTHER_CFLAGS", "$(OTHER_CFLAGS)", "${OTHER_CFLAGS}"):
  639. other_ccflags += self._Settings().get("OTHER_CFLAGS", [])
  640. else:
  641. other_ccflags.append(flag)
  642. cflags_cc += other_ccflags
  643. self.configname = None
  644. return cflags_cc
  645. def _AddObjectiveCGarbageCollectionFlags(self, flags):
  646. gc_policy = self._Settings().get("GCC_ENABLE_OBJC_GC", "unsupported")
  647. if gc_policy == "supported":
  648. flags.append("-fobjc-gc")
  649. elif gc_policy == "required":
  650. flags.append("-fobjc-gc-only")
  651. def _AddObjectiveCARCFlags(self, flags):
  652. if self._Test("CLANG_ENABLE_OBJC_ARC", "YES", default="NO"):
  653. flags.append("-fobjc-arc")
  654. def _AddObjectiveCMissingPropertySynthesisFlags(self, flags):
  655. if self._Test(
  656. "CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS", "YES", default="NO"
  657. ):
  658. flags.append("-Wobjc-missing-property-synthesis")
  659. def GetCflagsObjC(self, configname):
  660. """Returns flags that need to be added to .m compilations."""
  661. self.configname = configname
  662. cflags_objc = []
  663. self._AddObjectiveCGarbageCollectionFlags(cflags_objc)
  664. self._AddObjectiveCARCFlags(cflags_objc)
  665. self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc)
  666. self.configname = None
  667. return cflags_objc
  668. def GetCflagsObjCC(self, configname):
  669. """Returns flags that need to be added to .mm compilations."""
  670. self.configname = configname
  671. cflags_objcc = []
  672. self._AddObjectiveCGarbageCollectionFlags(cflags_objcc)
  673. self._AddObjectiveCARCFlags(cflags_objcc)
  674. self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc)
  675. if self._Test("GCC_OBJC_CALL_CXX_CDTORS", "YES", default="NO"):
  676. cflags_objcc.append("-fobjc-call-cxx-cdtors")
  677. self.configname = None
  678. return cflags_objcc
  679. def GetInstallNameBase(self):
  680. """Return DYLIB_INSTALL_NAME_BASE for this target."""
  681. # Xcode sets this for shared_libraries, and for nonbundled loadable_modules.
  682. if self.spec["type"] != "shared_library" and (
  683. self.spec["type"] != "loadable_module" or self._IsBundle()
  684. ):
  685. return None
  686. install_base = self.GetPerTargetSetting(
  687. "DYLIB_INSTALL_NAME_BASE",
  688. default="/Library/Frameworks" if self._IsBundle() else "/usr/local/lib",
  689. )
  690. return install_base
  691. def _StandardizePath(self, path):
  692. """Do :standardizepath processing for path."""
  693. # I'm not quite sure what :standardizepath does. Just call normpath(),
  694. # but don't let @executable_path/../foo collapse to foo.
  695. if "/" in path:
  696. prefix, rest = "", path
  697. if path.startswith("@"):
  698. prefix, rest = path.split("/", 1)
  699. rest = os.path.normpath(rest) # :standardizepath
  700. path = os.path.join(prefix, rest)
  701. return path
  702. def GetInstallName(self):
  703. """Return LD_DYLIB_INSTALL_NAME for this target."""
  704. # Xcode sets this for shared_libraries, and for nonbundled loadable_modules.
  705. if self.spec["type"] != "shared_library" and (
  706. self.spec["type"] != "loadable_module" or self._IsBundle()
  707. ):
  708. return None
  709. default_install_name = (
  710. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)"
  711. )
  712. install_name = self.GetPerTargetSetting(
  713. "LD_DYLIB_INSTALL_NAME", default=default_install_name
  714. )
  715. # Hardcode support for the variables used in chromium for now, to
  716. # unblock people using the make build.
  717. if "$" in install_name:
  718. assert install_name in (
  719. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/"
  720. "$(WRAPPER_NAME)/$(PRODUCT_NAME)",
  721. default_install_name,
  722. ), (
  723. "Variables in LD_DYLIB_INSTALL_NAME are not generally supported "
  724. "yet in target '%s' (got '%s')"
  725. % (self.spec["target_name"], install_name)
  726. )
  727. install_name = install_name.replace(
  728. "$(DYLIB_INSTALL_NAME_BASE:standardizepath)",
  729. self._StandardizePath(self.GetInstallNameBase()),
  730. )
  731. if self._IsBundle():
  732. # These are only valid for bundles, hence the |if|.
  733. install_name = install_name.replace(
  734. "$(WRAPPER_NAME)", self.GetWrapperName()
  735. )
  736. install_name = install_name.replace(
  737. "$(PRODUCT_NAME)", self.GetProductName()
  738. )
  739. else:
  740. assert "$(WRAPPER_NAME)" not in install_name
  741. assert "$(PRODUCT_NAME)" not in install_name
  742. install_name = install_name.replace(
  743. "$(EXECUTABLE_PATH)", self.GetExecutablePath()
  744. )
  745. return install_name
  746. def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path):
  747. """Checks if ldflag contains a filename and if so remaps it from
  748. gyp-directory-relative to build-directory-relative."""
  749. # This list is expanded on demand.
  750. # They get matched as:
  751. # -exported_symbols_list file
  752. # -Wl,exported_symbols_list file
  753. # -Wl,exported_symbols_list,file
  754. LINKER_FILE = r"(\S+)"
  755. WORD = r"\S+"
  756. linker_flags = [
  757. ["-exported_symbols_list", LINKER_FILE], # Needed for NaCl.
  758. ["-unexported_symbols_list", LINKER_FILE],
  759. ["-reexported_symbols_list", LINKER_FILE],
  760. ["-sectcreate", WORD, WORD, LINKER_FILE], # Needed for remoting.
  761. ]
  762. for flag_pattern in linker_flags:
  763. regex = re.compile("(?:-Wl,)?" + "[ ,]".join(flag_pattern))
  764. m = regex.match(ldflag)
  765. if m:
  766. ldflag = (
  767. ldflag[: m.start(1)]
  768. + gyp_to_build_path(m.group(1))
  769. + ldflag[m.end(1) :]
  770. )
  771. # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS,
  772. # TODO(thakis): Update ffmpeg.gyp):
  773. if ldflag.startswith("-L"):
  774. ldflag = "-L" + gyp_to_build_path(ldflag[len("-L") :])
  775. return ldflag
  776. def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
  777. """Returns flags that need to be passed to the linker.
  778. Args:
  779. configname: The name of the configuration to get ld flags for.
  780. product_dir: The directory where products such static and dynamic
  781. libraries are placed. This is added to the library search path.
  782. gyp_to_build_path: A function that converts paths relative to the
  783. current gyp file to paths relative to the build directory.
  784. """
  785. self.configname = configname
  786. ldflags = []
  787. # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS
  788. # can contain entries that depend on this. Explicitly absolutify these.
  789. for ldflag in self._Settings().get("OTHER_LDFLAGS", []):
  790. ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path))
  791. if self._Test("DEAD_CODE_STRIPPING", "YES", default="NO"):
  792. ldflags.append("-Wl,-dead_strip")
  793. if self._Test("PREBINDING", "YES", default="NO"):
  794. ldflags.append("-Wl,-prebind")
  795. self._Appendf(
  796. ldflags, "DYLIB_COMPATIBILITY_VERSION", "-compatibility_version %s"
  797. )
  798. self._Appendf(ldflags, "DYLIB_CURRENT_VERSION", "-current_version %s")
  799. self._AppendPlatformVersionMinFlags(ldflags)
  800. if "SDKROOT" in self._Settings() and self._SdkPath():
  801. ldflags.append("-isysroot")
  802. ldflags.append(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("-Wl,-order_file")
  807. ldflags.append("-Wl," + gyp_to_build_path(self._Settings()["ORDER_FILE"]))
  808. if not gyp.common.CrossCompileRequested():
  809. if arch is not None:
  810. archs = [arch]
  811. else:
  812. assert self.configname
  813. archs = self.GetActiveArchs(self.configname)
  814. if len(archs) != 1:
  815. # TODO: Supporting fat binaries will be annoying.
  816. self._WarnUnimplemented("ARCHS")
  817. archs = ["i386"]
  818. # Avoid quoting the space between -arch and the arch name
  819. ldflags.append("-arch")
  820. ldflags.append(archs[0])
  821. # Xcode adds the product directory by default.
  822. # Rewrite -L. to -L./ to work around http://www.openradar.me/25313838
  823. ldflags.append("-L" + (product_dir if product_dir != "." else "./"))
  824. install_name = self.GetInstallName()
  825. if install_name and self.spec["type"] != "loadable_module":
  826. ldflags.append("-install_name")
  827. ldflags.append(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")
  842. ldflags.append("XCTest")
  843. is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension()
  844. if sdk_root and is_extension:
  845. # Adds the link flags for extensions. These flags are common for all
  846. # extensions and provide loader and main function.
  847. # These flags reflect the compilation options used by xcode to compile
  848. # extensions.
  849. xcode_version, _ = XcodeVersion()
  850. if xcode_version < "0900":
  851. ldflags.append("-lpkstart")
  852. ldflags.append(
  853. sdk_root
  854. + "/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit"
  855. )
  856. else:
  857. ldflags.append("-e")
  858. ldflags.append("_NSExtensionMain")
  859. ldflags.append("-fapplication-extension")
  860. self._Appendf(ldflags, "CLANG_CXX_LIBRARY", "-stdlib=%s")
  861. self.configname = None
  862. return ldflags
  863. def GetLibtoolflags(self, configname):
  864. """Returns flags that need to be passed to the static linker.
  865. Args:
  866. configname: The name of the configuration to get ld flags for.
  867. """
  868. self.configname = configname
  869. libtoolflags = []
  870. for libtoolflag in self._Settings().get("OTHER_LDFLAGS", []):
  871. libtoolflags.append(libtoolflag)
  872. # TODO(thakis): ARCHS?
  873. self.configname = None
  874. return libtoolflags
  875. def GetPerTargetSettings(self):
  876. """Gets a list of all the per-target settings. This will only fetch keys
  877. whose values are the same across all configurations."""
  878. first_pass = True
  879. result = {}
  880. for configname in sorted(self.xcode_settings.keys()):
  881. if first_pass:
  882. result = dict(self.xcode_settings[configname])
  883. first_pass = False
  884. else:
  885. for key, value in self.xcode_settings[configname].items():
  886. if key not in result:
  887. continue
  888. elif result[key] != value:
  889. del result[key]
  890. return result
  891. def GetPerConfigSetting(self, setting, configname, default=None):
  892. if configname in self.xcode_settings:
  893. return self.xcode_settings[configname].get(setting, default)
  894. else:
  895. return self.GetPerTargetSetting(setting, default)
  896. def GetPerTargetSetting(self, setting, default=None):
  897. """Tries to get xcode_settings.setting from spec. Assumes that the setting
  898. has the same value in all configurations and throws otherwise."""
  899. is_first_pass = True
  900. result = None
  901. for configname in sorted(self.xcode_settings.keys()):
  902. if is_first_pass:
  903. result = self.xcode_settings[configname].get(setting, None)
  904. is_first_pass = False
  905. else:
  906. assert result == self.xcode_settings[configname].get(setting, None), (
  907. "Expected per-target setting for '%s', got per-config setting "
  908. "(target %s)" % (setting, self.spec["target_name"])
  909. )
  910. if result is None:
  911. return default
  912. return result
  913. def _GetStripPostbuilds(self, configname, output_binary, quiet):
  914. """Returns a list of shell commands that contain the shell commands
  915. necessary to strip this target's binary. These should be run as postbuilds
  916. before the actual postbuilds run."""
  917. self.configname = configname
  918. result = []
  919. if self._Test("DEPLOYMENT_POSTPROCESSING", "YES", default="NO") and self._Test(
  920. "STRIP_INSTALLED_PRODUCT", "YES", default="NO"
  921. ):
  922. default_strip_style = "debugging"
  923. if (
  924. self.spec["type"] == "loadable_module" or self._IsIosAppExtension()
  925. ) and self._IsBundle():
  926. default_strip_style = "non-global"
  927. elif self.spec["type"] == "executable":
  928. default_strip_style = "all"
  929. strip_style = self._Settings().get("STRIP_STYLE", default_strip_style)
  930. strip_flags = {"all": "", "non-global": "-x", "debugging": "-S"}[
  931. strip_style
  932. ]
  933. explicit_strip_flags = self._Settings().get("STRIPFLAGS", "")
  934. if explicit_strip_flags:
  935. strip_flags += " " + _NormalizeEnvVarReferences(explicit_strip_flags)
  936. if not quiet:
  937. result.append("echo STRIP\\(%s\\)" % self.spec["target_name"])
  938. result.append(f"strip {strip_flags} {output_binary}")
  939. self.configname = None
  940. return result
  941. def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet):
  942. """Returns a list of shell commands that contain the shell commands
  943. necessary to massage this target's debug information. These should be run
  944. as postbuilds before the actual postbuilds run."""
  945. self.configname = configname
  946. # For static libraries, no dSYMs are created.
  947. result = []
  948. if (
  949. self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES")
  950. and self._Test(
  951. "DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym", default="dwarf"
  952. )
  953. and self.spec["type"] != "static_library"
  954. ):
  955. if not quiet:
  956. result.append("echo DSYMUTIL\\(%s\\)" % self.spec["target_name"])
  957. result.append("dsymutil {} -o {}".format(output_binary, output + ".dSYM"))
  958. self.configname = None
  959. return result
  960. def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False):
  961. """Returns a list of shell commands that contain the shell commands
  962. to run as postbuilds for this target, before the actual postbuilds."""
  963. # dSYMs need to build before stripping happens.
  964. return self._GetDebugInfoPostbuilds(
  965. configname, output, output_binary, quiet
  966. ) + self._GetStripPostbuilds(configname, output_binary, quiet)
  967. def _GetIOSPostbuilds(self, configname, output_binary):
  968. """Return a shell command to codesign the iOS output binary so it can
  969. be deployed to a device. This should be run as the very last step of the
  970. build."""
  971. if not (
  972. (self.isIOS
  973. and (self.spec["type"] == "executable" or self._IsXCTest()))
  974. or self.IsIosFramework()
  975. ):
  976. return []
  977. postbuilds = []
  978. product_name = self.GetFullProductName()
  979. settings = self.xcode_settings[configname]
  980. # Xcode expects XCTests to be copied into the TEST_HOST dir.
  981. if self._IsXCTest():
  982. source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name)
  983. test_host = os.path.dirname(settings.get("TEST_HOST"))
  984. xctest_destination = os.path.join(test_host, "PlugIns", product_name)
  985. postbuilds.extend([f"ditto {source} {xctest_destination}"])
  986. key = self._GetIOSCodeSignIdentityKey(settings)
  987. if not key:
  988. return postbuilds
  989. # Warn for any unimplemented signing xcode keys.
  990. unimpl = ["OTHER_CODE_SIGN_FLAGS"]
  991. unimpl = set(unimpl) & set(self.xcode_settings[configname].keys())
  992. if unimpl:
  993. print(
  994. "Warning: Some codesign keys not implemented, ignoring: %s"
  995. % ", ".join(sorted(unimpl))
  996. )
  997. if self._IsXCTest():
  998. # For device xctests, Xcode copies two extra frameworks into $TEST_HOST.
  999. test_host = os.path.dirname(settings.get("TEST_HOST"))
  1000. frameworks_dir = os.path.join(test_host, "Frameworks")
  1001. platform_root = self._XcodePlatformPath(configname)
  1002. frameworks = [
  1003. "Developer/Library/PrivateFrameworks/IDEBundleInjection.framework",
  1004. "Developer/Library/Frameworks/XCTest.framework",
  1005. ]
  1006. for framework in frameworks:
  1007. source = os.path.join(platform_root, framework)
  1008. destination = os.path.join(frameworks_dir, os.path.basename(framework))
  1009. postbuilds.extend([f"ditto {source} {destination}"])
  1010. # Then re-sign everything with 'preserve=True'
  1011. postbuilds.extend(
  1012. [
  1013. '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1014. % (
  1015. sys.executable,
  1016. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1017. key,
  1018. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1019. settings.get("PROVISIONING_PROFILE", ""),
  1020. destination,
  1021. True,
  1022. )
  1023. ]
  1024. )
  1025. plugin_dir = os.path.join(test_host, "PlugIns")
  1026. targets = [os.path.join(plugin_dir, product_name), test_host]
  1027. for target in targets:
  1028. postbuilds.extend(
  1029. [
  1030. '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1031. % (
  1032. sys.executable,
  1033. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1034. key,
  1035. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1036. settings.get("PROVISIONING_PROFILE", ""),
  1037. target,
  1038. True,
  1039. )
  1040. ]
  1041. )
  1042. postbuilds.extend(
  1043. [
  1044. '%s %s code-sign-bundle "%s" "%s" "%s" "%s" %s'
  1045. % (
  1046. sys.executable,
  1047. os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"),
  1048. key,
  1049. settings.get("CODE_SIGN_ENTITLEMENTS", ""),
  1050. settings.get("PROVISIONING_PROFILE", ""),
  1051. os.path.join("${BUILT_PRODUCTS_DIR}", product_name),
  1052. False,
  1053. )
  1054. ]
  1055. )
  1056. return postbuilds
  1057. def _GetIOSCodeSignIdentityKey(self, settings):
  1058. identity = settings.get("CODE_SIGN_IDENTITY")
  1059. if not identity:
  1060. return None
  1061. if identity not in XcodeSettings._codesigning_key_cache:
  1062. output = subprocess.check_output(
  1063. ["security", "find-identity", "-p", "codesigning", "-v"]
  1064. )
  1065. for line in output.splitlines():
  1066. if identity in line:
  1067. fingerprint = line.split()[1]
  1068. cache = XcodeSettings._codesigning_key_cache
  1069. assert identity not in cache or fingerprint == cache[identity], (
  1070. "Multiple codesigning fingerprints for identity: %s" % identity
  1071. )
  1072. XcodeSettings._codesigning_key_cache[identity] = fingerprint
  1073. return XcodeSettings._codesigning_key_cache.get(identity, "")
  1074. def AddImplicitPostbuilds(
  1075. self, configname, output, output_binary, postbuilds=[], quiet=False
  1076. ):
  1077. """Returns a list of shell commands that should run before and after
  1078. |postbuilds|."""
  1079. assert output_binary is not None
  1080. pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet)
  1081. post = self._GetIOSPostbuilds(configname, output_binary)
  1082. return pre + postbuilds + post
  1083. def _AdjustLibrary(self, library, config_name=None):
  1084. if library.endswith(".framework"):
  1085. l_flag = "-framework " + os.path.splitext(os.path.basename(library))[0]
  1086. else:
  1087. m = self.library_re.match(library)
  1088. l_flag = "-l" + m.group(1) if m else library
  1089. sdk_root = self._SdkPath(config_name)
  1090. if not sdk_root:
  1091. sdk_root = ""
  1092. # Xcode 7 started shipping with ".tbd" (text based stubs) files instead of
  1093. # ".dylib" without providing a real support for them. What it does, for
  1094. # "/usr/lib" libraries, is do "-L/usr/lib -lname" which is dependent on the
  1095. # library order and cause collision when building Chrome.
  1096. #
  1097. # Instead substitute ".tbd" to ".dylib" in the generated project when the
  1098. # following conditions are both true:
  1099. # - library is referenced in the gyp file as "$(SDKROOT)/**/*.dylib",
  1100. # - the ".dylib" file does not exists but a ".tbd" file do.
  1101. library = l_flag.replace("$(SDKROOT)", sdk_root)
  1102. if l_flag.startswith("$(SDKROOT)"):
  1103. basename, ext = os.path.splitext(library)
  1104. if ext == ".dylib" and not os.path.exists(library):
  1105. tbd_library = basename + ".tbd"
  1106. if os.path.exists(tbd_library):
  1107. library = tbd_library
  1108. return library
  1109. def AdjustLibraries(self, libraries, config_name=None):
  1110. """Transforms entries like 'Cocoa.framework' in libraries into entries like
  1111. '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc.
  1112. """
  1113. libraries = [self._AdjustLibrary(library, config_name) for library in libraries]
  1114. return libraries
  1115. def _BuildMachineOSBuild(self):
  1116. return GetStdout(["sw_vers", "-buildVersion"])
  1117. def _XcodeIOSDeviceFamily(self, configname):
  1118. family = self.xcode_settings[configname].get("TARGETED_DEVICE_FAMILY", "1")
  1119. return [int(x) for x in family.split(",")]
  1120. def GetExtraPlistItems(self, configname=None):
  1121. """Returns a dictionary with extra items to insert into Info.plist."""
  1122. if configname not in XcodeSettings._plist_cache:
  1123. cache = {}
  1124. cache["BuildMachineOSBuild"] = self._BuildMachineOSBuild()
  1125. xcode_version, xcode_build = XcodeVersion()
  1126. cache["DTXcode"] = xcode_version
  1127. cache["DTXcodeBuild"] = xcode_build
  1128. compiler = self.xcode_settings[configname].get("GCC_VERSION")
  1129. if compiler is not None:
  1130. cache["DTCompiler"] = compiler
  1131. sdk_root = self._SdkRoot(configname)
  1132. if not sdk_root:
  1133. sdk_root = self._DefaultSdkRoot()
  1134. sdk_version = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-version")
  1135. cache["DTSDKName"] = sdk_root + (sdk_version or "")
  1136. if xcode_version >= "0720":
  1137. cache["DTSDKBuild"] = self._GetSdkVersionInfoItem(
  1138. sdk_root, "--show-sdk-build-version"
  1139. )
  1140. elif xcode_version >= "0430":
  1141. cache["DTSDKBuild"] = sdk_version
  1142. else:
  1143. cache["DTSDKBuild"] = cache["BuildMachineOSBuild"]
  1144. if self.isIOS:
  1145. cache["MinimumOSVersion"] = self.xcode_settings[configname].get(
  1146. "IPHONEOS_DEPLOYMENT_TARGET"
  1147. )
  1148. cache["DTPlatformName"] = sdk_root
  1149. cache["DTPlatformVersion"] = sdk_version
  1150. if configname.endswith("iphoneos"):
  1151. cache["CFBundleSupportedPlatforms"] = ["iPhoneOS"]
  1152. cache["DTPlatformBuild"] = cache["DTSDKBuild"]
  1153. else:
  1154. cache["CFBundleSupportedPlatforms"] = ["iPhoneSimulator"]
  1155. # This is weird, but Xcode sets DTPlatformBuild to an empty field
  1156. # for simulator builds.
  1157. cache["DTPlatformBuild"] = ""
  1158. XcodeSettings._plist_cache[configname] = cache
  1159. # Include extra plist items that are per-target, not per global
  1160. # XcodeSettings.
  1161. items = dict(XcodeSettings._plist_cache[configname])
  1162. if self.isIOS:
  1163. items["UIDeviceFamily"] = self._XcodeIOSDeviceFamily(configname)
  1164. return items
  1165. def _DefaultSdkRoot(self):
  1166. """Returns the default SDKROOT to use.
  1167. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode
  1168. project, then the environment variable was empty. Starting with this
  1169. version, Xcode uses the name of the newest SDK installed.
  1170. """
  1171. xcode_version, _ = XcodeVersion()
  1172. if xcode_version < "0500":
  1173. return ""
  1174. default_sdk_path = self._XcodeSdkPath("")
  1175. default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path)
  1176. if default_sdk_root:
  1177. return default_sdk_root
  1178. try:
  1179. all_sdks = GetStdout(["xcodebuild", "-showsdks"])
  1180. except GypError:
  1181. # If xcodebuild fails, there will be no valid SDKs
  1182. return ""
  1183. for line in all_sdks.splitlines():
  1184. items = line.split()
  1185. if len(items) >= 3 and items[-2] == "-sdk":
  1186. sdk_root = items[-1]
  1187. sdk_path = self._XcodeSdkPath(sdk_root)
  1188. if sdk_path == default_sdk_path:
  1189. return sdk_root
  1190. return ""
  1191. class MacPrefixHeader:
  1192. """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature.
  1193. This feature consists of several pieces:
  1194. * If GCC_PREFIX_HEADER is present, all compilations in that project get an
  1195. additional |-include path_to_prefix_header| cflag.
  1196. * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is
  1197. instead compiled, and all other compilations in the project get an
  1198. additional |-include path_to_compiled_header| instead.
  1199. + Compiled prefix headers have the extension gch. There is one gch file for
  1200. every language used in the project (c, cc, m, mm), since gch files for
  1201. different languages aren't compatible.
  1202. + gch files themselves are built with the target's normal cflags, but they
  1203. obviously don't get the |-include| flag. Instead, they need a -x flag that
  1204. describes their language.
  1205. + All o files in the target need to depend on the gch file, to make sure
  1206. it's built before any o file is built.
  1207. This class helps with some of these tasks, but it needs help from the build
  1208. system for writing dependencies to the gch files, for writing build commands
  1209. for the gch files, and for figuring out the location of the gch files.
  1210. """
  1211. def __init__(
  1212. self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output
  1213. ):
  1214. """If xcode_settings is None, all methods on this class are no-ops.
  1215. Args:
  1216. gyp_path_to_build_path: A function that takes a gyp-relative path,
  1217. and returns a path relative to the build directory.
  1218. gyp_path_to_build_output: A function that takes a gyp-relative path and
  1219. a language code ('c', 'cc', 'm', or 'mm'), and that returns a path
  1220. to where the output of precompiling that path for that language
  1221. should be placed (without the trailing '.gch').
  1222. """
  1223. # This doesn't support per-configuration prefix headers. Good enough
  1224. # for now.
  1225. self.header = None
  1226. self.compile_headers = False
  1227. if xcode_settings:
  1228. self.header = xcode_settings.GetPerTargetSetting("GCC_PREFIX_HEADER")
  1229. self.compile_headers = (
  1230. xcode_settings.GetPerTargetSetting(
  1231. "GCC_PRECOMPILE_PREFIX_HEADER", default="NO"
  1232. )
  1233. != "NO"
  1234. )
  1235. self.compiled_headers = {}
  1236. if self.header:
  1237. if self.compile_headers:
  1238. for lang in ["c", "cc", "m", "mm"]:
  1239. self.compiled_headers[lang] = gyp_path_to_build_output(
  1240. self.header, lang
  1241. )
  1242. self.header = gyp_path_to_build_path(self.header)
  1243. def _CompiledHeader(self, lang, arch):
  1244. assert self.compile_headers
  1245. h = self.compiled_headers[lang]
  1246. if arch:
  1247. h += "." + arch
  1248. return h
  1249. def GetInclude(self, lang, arch=None):
  1250. """Gets the cflags to include the prefix header for language |lang|."""
  1251. if self.compile_headers and lang in self.compiled_headers:
  1252. return "-include %s" % self._CompiledHeader(lang, arch)
  1253. elif self.header:
  1254. return "-include %s" % self.header
  1255. else:
  1256. return ""
  1257. def _Gch(self, lang, arch):
  1258. """Returns the actual file name of the prefix header for language |lang|."""
  1259. assert self.compile_headers
  1260. return self._CompiledHeader(lang, arch) + ".gch"
  1261. def GetObjDependencies(self, sources, objs, arch=None):
  1262. """Given a list of source files and the corresponding object files, returns
  1263. a list of (source, object, gch) tuples, where |gch| is the build-directory
  1264. relative path to the gch file each object file depends on. |compilable[i]|
  1265. has to be the source file belonging to |objs[i]|."""
  1266. if not self.header or not self.compile_headers:
  1267. return []
  1268. result = []
  1269. for source, obj in zip(sources, objs):
  1270. ext = os.path.splitext(source)[1]
  1271. lang = {
  1272. ".c": "c",
  1273. ".cpp": "cc",
  1274. ".cc": "cc",
  1275. ".cxx": "cc",
  1276. ".m": "m",
  1277. ".mm": "mm",
  1278. }.get(ext, None)
  1279. if lang:
  1280. result.append((source, obj, self._Gch(lang, arch)))
  1281. return result
  1282. def GetPchBuildCommands(self, arch=None):
  1283. """Returns [(path_to_gch, language_flag, language, header)].
  1284. |path_to_gch| and |header| are relative to the build directory.
  1285. """
  1286. if not self.header or not self.compile_headers:
  1287. return []
  1288. return [
  1289. (self._Gch("c", arch), "-x c-header", "c", self.header),
  1290. (self._Gch("cc", arch), "-x c++-header", "cc", self.header),
  1291. (self._Gch("m", arch), "-x objective-c-header", "m", self.header),
  1292. (self._Gch("mm", arch), "-x objective-c++-header", "mm", self.header),
  1293. ]
  1294. def XcodeVersion():
  1295. """Returns a tuple of version and build version of installed Xcode."""
  1296. # `xcodebuild -version` output looks like
  1297. # Xcode 4.6.3
  1298. # Build version 4H1503
  1299. # or like
  1300. # Xcode 3.2.6
  1301. # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0
  1302. # BuildVersion: 10M2518
  1303. # Convert that to ('0463', '4H1503') or ('0326', '10M2518').
  1304. global XCODE_VERSION_CACHE
  1305. if XCODE_VERSION_CACHE:
  1306. return XCODE_VERSION_CACHE
  1307. version = ""
  1308. build = ""
  1309. try:
  1310. version_list = GetStdoutQuiet(["xcodebuild", "-version"]).splitlines()
  1311. # In some circumstances xcodebuild exits 0 but doesn't return
  1312. # the right results; for example, a user on 10.7 or 10.8 with
  1313. # a bogus path set via xcode-select
  1314. # In that case this may be a CLT-only install so fall back to
  1315. # checking that version.
  1316. if len(version_list) < 2:
  1317. raise GypError("xcodebuild returned unexpected results")
  1318. version = version_list[0].split()[-1] # Last word on first line
  1319. build = version_list[-1].split()[-1] # Last word on last line
  1320. except GypError: # Xcode not installed so look for XCode Command Line Tools
  1321. version = CLTVersion() # macOS Catalina returns 11.0.0.0.1.1567737322
  1322. if not version:
  1323. raise GypError("No Xcode or CLT version detected!")
  1324. # Be careful to convert "4.2.3" to "0423" and "11.0.0" to "1100":
  1325. version = version.split(".")[:3] # Just major, minor, micro
  1326. version[0] = version[0].zfill(2) # Add a leading zero if major is one digit
  1327. version = ("".join(version) + "00")[:4] # Limit to exactly four characters
  1328. XCODE_VERSION_CACHE = (version, build)
  1329. return XCODE_VERSION_CACHE
  1330. # This function ported from the logic in Homebrew's CLT version check
  1331. def CLTVersion():
  1332. """Returns the version of command-line tools from pkgutil."""
  1333. # pkgutil output looks like
  1334. # package-id: com.apple.pkg.CLTools_Executables
  1335. # version: 5.0.1.0.1.1382131676
  1336. # volume: /
  1337. # location: /
  1338. # install-time: 1382544035
  1339. # groups: com.apple.FindSystemFiles.pkg-group
  1340. # com.apple.DevToolsBoth.pkg-group
  1341. # com.apple.DevToolsNonRelocatableShared.pkg-group
  1342. STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo"
  1343. FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI"
  1344. MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables"
  1345. regex = re.compile("version: (?P<version>.+)")
  1346. for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]:
  1347. try:
  1348. output = GetStdout(["/usr/sbin/pkgutil", "--pkg-info", key])
  1349. return re.search(regex, output).groupdict()["version"]
  1350. except GypError:
  1351. continue
  1352. regex = re.compile(r"Command Line Tools for Xcode\s+(?P<version>\S+)")
  1353. try:
  1354. output = GetStdout(["/usr/sbin/softwareupdate", "--history"])
  1355. return re.search(regex, output).groupdict()["version"]
  1356. except GypError:
  1357. return None
  1358. def GetStdoutQuiet(cmdlist):
  1359. """Returns the content of standard output returned by invoking |cmdlist|.
  1360. Ignores the stderr.
  1361. Raises |GypError| if the command return with a non-zero return code."""
  1362. job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1363. out = job.communicate()[0].decode("utf-8")
  1364. if job.returncode != 0:
  1365. raise GypError("Error %d running %s" % (job.returncode, cmdlist[0]))
  1366. return out.rstrip("\n")
  1367. def GetStdout(cmdlist):
  1368. """Returns the content of standard output returned by invoking |cmdlist|.
  1369. Raises |GypError| if the command return with a non-zero return code."""
  1370. job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE)
  1371. out = job.communicate()[0].decode("utf-8")
  1372. if job.returncode != 0:
  1373. sys.stderr.write(out + "\n")
  1374. raise GypError("Error %d running %s" % (job.returncode, cmdlist[0]))
  1375. return out.rstrip("\n")
  1376. def MergeGlobalXcodeSettingsToSpec(global_dict, spec):
  1377. """Merges the global xcode_settings dictionary into each configuration of the
  1378. target represented by spec. For keys that are both in the global and the local
  1379. xcode_settings dict, the local key gets precedence.
  1380. """
  1381. # The xcode generator special-cases global xcode_settings and does something
  1382. # that amounts to merging in the global xcode_settings into each local
  1383. # xcode_settings dict.
  1384. global_xcode_settings = global_dict.get("xcode_settings", {})
  1385. for config in spec["configurations"].values():
  1386. if "xcode_settings" in config:
  1387. new_settings = global_xcode_settings.copy()
  1388. new_settings.update(config["xcode_settings"])
  1389. config["xcode_settings"] = new_settings
  1390. def IsMacBundle(flavor, spec):
  1391. """Returns if |spec| should be treated as a bundle.
  1392. Bundles are directories with a certain subdirectory structure, instead of
  1393. just a single file. Bundle rules do not produce a binary but also package
  1394. resources into that directory."""
  1395. is_mac_bundle = (
  1396. int(spec.get("mac_xctest_bundle", 0)) != 0
  1397. or int(spec.get("mac_xcuitest_bundle", 0)) != 0
  1398. or (int(spec.get("mac_bundle", 0)) != 0 and flavor == "mac")
  1399. )
  1400. if is_mac_bundle:
  1401. assert spec["type"] != "none", (
  1402. 'mac_bundle targets cannot have type none (target "%s")'
  1403. % spec["target_name"]
  1404. )
  1405. return is_mac_bundle
  1406. def GetMacBundleResources(product_dir, xcode_settings, resources):
  1407. """Yields (output, resource) pairs for every resource in |resources|.
  1408. Only call this for mac bundle targets.
  1409. Args:
  1410. product_dir: Path to the directory containing the output bundle,
  1411. relative to the build directory.
  1412. xcode_settings: The XcodeSettings of the current target.
  1413. resources: A list of bundle resources, relative to the build directory.
  1414. """
  1415. dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder())
  1416. for res in resources:
  1417. output = dest
  1418. # The make generator doesn't support it, so forbid it everywhere
  1419. # to keep the generators more interchangeable.
  1420. assert " " not in res, "Spaces in resource filenames not supported (%s)" % res
  1421. # Split into (path,file).
  1422. res_parts = os.path.split(res)
  1423. # Now split the path into (prefix,maybe.lproj).
  1424. lproj_parts = os.path.split(res_parts[0])
  1425. # If the resource lives in a .lproj bundle, add that to the destination.
  1426. if lproj_parts[1].endswith(".lproj"):
  1427. output = os.path.join(output, lproj_parts[1])
  1428. output = os.path.join(output, res_parts[1])
  1429. # Compiled XIB files are referred to by .nib.
  1430. if output.endswith(".xib"):
  1431. output = os.path.splitext(output)[0] + ".nib"
  1432. # Compiled storyboard files are referred to by .storyboardc.
  1433. if output.endswith(".storyboard"):
  1434. output = os.path.splitext(output)[0] + ".storyboardc"
  1435. yield output, res
  1436. def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path):
  1437. """Returns (info_plist, dest_plist, defines, extra_env), where:
  1438. * |info_plist| is the source plist path, relative to the
  1439. build directory,
  1440. * |dest_plist| is the destination plist path, relative to the
  1441. build directory,
  1442. * |defines| is a list of preprocessor defines (empty if the plist
  1443. shouldn't be preprocessed,
  1444. * |extra_env| is a dict of env variables that should be exported when
  1445. invoking |mac_tool copy-info-plist|.
  1446. Only call this for mac bundle targets.
  1447. Args:
  1448. product_dir: Path to the directory containing the output bundle,
  1449. relative to the build directory.
  1450. xcode_settings: The XcodeSettings of the current target.
  1451. gyp_to_build_path: A function that converts paths relative to the
  1452. current gyp file to paths relative to the build directory.
  1453. """
  1454. info_plist = xcode_settings.GetPerTargetSetting("INFOPLIST_FILE")
  1455. if not info_plist:
  1456. return None, None, [], {}
  1457. # The make generator doesn't support it, so forbid it everywhere
  1458. # to keep the generators more interchangeable.
  1459. assert " " not in info_plist, (
  1460. "Spaces in Info.plist filenames not supported (%s)" % info_plist
  1461. )
  1462. info_plist = gyp_path_to_build_path(info_plist)
  1463. # If explicitly set to preprocess the plist, invoke the C preprocessor and
  1464. # specify any defines as -D flags.
  1465. if (
  1466. xcode_settings.GetPerTargetSetting("INFOPLIST_PREPROCESS", default="NO")
  1467. == "YES"
  1468. ):
  1469. # Create an intermediate file based on the path.
  1470. defines = shlex.split(
  1471. xcode_settings.GetPerTargetSetting(
  1472. "INFOPLIST_PREPROCESSOR_DEFINITIONS", default=""
  1473. )
  1474. )
  1475. else:
  1476. defines = []
  1477. dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath())
  1478. extra_env = xcode_settings.GetPerTargetSettings()
  1479. return info_plist, dest_plist, defines, extra_env
  1480. def _GetXcodeEnv(
  1481. xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None
  1482. ):
  1483. """Return the environment variables that Xcode would set. See
  1484. 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
  1485. for a full list.
  1486. Args:
  1487. xcode_settings: An XcodeSettings object. If this is None, this function
  1488. returns an empty dict.
  1489. built_products_dir: Absolute path to the built products dir.
  1490. srcroot: Absolute path to the source root.
  1491. configuration: The build configuration name.
  1492. additional_settings: An optional dict with more values to add to the
  1493. result.
  1494. """
  1495. if not xcode_settings:
  1496. return {}
  1497. # This function is considered a friend of XcodeSettings, so let it reach into
  1498. # its implementation details.
  1499. spec = xcode_settings.spec
  1500. # These are filled in on an as-needed basis.
  1501. env = {
  1502. "BUILT_FRAMEWORKS_DIR": built_products_dir,
  1503. "BUILT_PRODUCTS_DIR": built_products_dir,
  1504. "CONFIGURATION": configuration,
  1505. "PRODUCT_NAME": xcode_settings.GetProductName(),
  1506. # For FULL_PRODUCT_NAME see:
  1507. # /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec # noqa: E501
  1508. "SRCROOT": srcroot,
  1509. "SOURCE_ROOT": "${SRCROOT}",
  1510. # This is not true for static libraries, but currently the env is only
  1511. # written for bundles:
  1512. "TARGET_BUILD_DIR": built_products_dir,
  1513. "TEMP_DIR": "${TMPDIR}",
  1514. "XCODE_VERSION_ACTUAL": XcodeVersion()[0],
  1515. }
  1516. if xcode_settings.GetPerConfigSetting("SDKROOT", configuration):
  1517. env["SDKROOT"] = xcode_settings._SdkPath(configuration)
  1518. else:
  1519. env["SDKROOT"] = ""
  1520. if xcode_settings.mac_toolchain_dir:
  1521. env["DEVELOPER_DIR"] = xcode_settings.mac_toolchain_dir
  1522. if spec["type"] in (
  1523. "executable",
  1524. "static_library",
  1525. "shared_library",
  1526. "loadable_module",
  1527. ):
  1528. env["EXECUTABLE_NAME"] = xcode_settings.GetExecutableName()
  1529. env["EXECUTABLE_PATH"] = xcode_settings.GetExecutablePath()
  1530. env["FULL_PRODUCT_NAME"] = xcode_settings.GetFullProductName()
  1531. mach_o_type = xcode_settings.GetMachOType()
  1532. if mach_o_type:
  1533. env["MACH_O_TYPE"] = mach_o_type
  1534. env["PRODUCT_TYPE"] = xcode_settings.GetProductType()
  1535. if xcode_settings._IsBundle():
  1536. # xcodeproj_file.py sets the same Xcode subfolder value for this as for
  1537. # FRAMEWORKS_FOLDER_PATH so Xcode builds will actually use FFP's value.
  1538. env["BUILT_FRAMEWORKS_DIR"] = os.path.join(
  1539. built_products_dir + os.sep + xcode_settings.GetBundleFrameworksFolderPath()
  1540. )
  1541. env["CONTENTS_FOLDER_PATH"] = xcode_settings.GetBundleContentsFolderPath()
  1542. env["EXECUTABLE_FOLDER_PATH"] = xcode_settings.GetBundleExecutableFolderPath()
  1543. env[
  1544. "UNLOCALIZED_RESOURCES_FOLDER_PATH"
  1545. ] = xcode_settings.GetBundleResourceFolder()
  1546. env["JAVA_FOLDER_PATH"] = xcode_settings.GetBundleJavaFolderPath()
  1547. env["FRAMEWORKS_FOLDER_PATH"] = xcode_settings.GetBundleFrameworksFolderPath()
  1548. env[
  1549. "SHARED_FRAMEWORKS_FOLDER_PATH"
  1550. ] = xcode_settings.GetBundleSharedFrameworksFolderPath()
  1551. env[
  1552. "SHARED_SUPPORT_FOLDER_PATH"
  1553. ] = xcode_settings.GetBundleSharedSupportFolderPath()
  1554. env["PLUGINS_FOLDER_PATH"] = xcode_settings.GetBundlePlugInsFolderPath()
  1555. env["XPCSERVICES_FOLDER_PATH"] = xcode_settings.GetBundleXPCServicesFolderPath()
  1556. env["INFOPLIST_PATH"] = xcode_settings.GetBundlePlistPath()
  1557. env["WRAPPER_NAME"] = xcode_settings.GetWrapperName()
  1558. install_name = xcode_settings.GetInstallName()
  1559. if install_name:
  1560. env["LD_DYLIB_INSTALL_NAME"] = install_name
  1561. install_name_base = xcode_settings.GetInstallNameBase()
  1562. if install_name_base:
  1563. env["DYLIB_INSTALL_NAME_BASE"] = install_name_base
  1564. xcode_version, _ = XcodeVersion()
  1565. if xcode_version >= "0500" and not env.get("SDKROOT"):
  1566. sdk_root = xcode_settings._SdkRoot(configuration)
  1567. if not sdk_root:
  1568. sdk_root = xcode_settings._XcodeSdkPath("")
  1569. if sdk_root is None:
  1570. sdk_root = ""
  1571. env["SDKROOT"] = sdk_root
  1572. if not additional_settings:
  1573. additional_settings = {}
  1574. else:
  1575. # Flatten lists to strings.
  1576. for k in additional_settings:
  1577. if not isinstance(additional_settings[k], str):
  1578. additional_settings[k] = " ".join(additional_settings[k])
  1579. additional_settings.update(env)
  1580. for k in additional_settings:
  1581. additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k])
  1582. return additional_settings
  1583. def _NormalizeEnvVarReferences(str):
  1584. """Takes a string containing variable references in the form ${FOO}, $(FOO),
  1585. or $FOO, and returns a string with all variable references in the form ${FOO}.
  1586. """
  1587. # $FOO -> ${FOO}
  1588. str = re.sub(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", r"${\1}", str)
  1589. # $(FOO) -> ${FOO}
  1590. matches = re.findall(r"(\$\(([a-zA-Z0-9\-_]+)\))", str)
  1591. for match in matches:
  1592. to_replace, variable = match
  1593. assert "$(" not in match, "$($(FOO)) variables not supported: " + match
  1594. str = str.replace(to_replace, "${" + variable + "}")
  1595. return str
  1596. def ExpandEnvVars(string, expansions):
  1597. """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the
  1598. expansions list. If the variable expands to something that references
  1599. another variable, this variable is expanded as well if it's in env --
  1600. until no variables present in env are left."""
  1601. for k, v in reversed(expansions):
  1602. string = string.replace("${" + k + "}", v)
  1603. string = string.replace("$(" + k + ")", v)
  1604. string = string.replace("$" + k, v)
  1605. return string
  1606. def _TopologicallySortedEnvVarKeys(env):
  1607. """Takes a dict |env| whose values are strings that can refer to other keys,
  1608. for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of
  1609. env such that key2 is after key1 in L if env[key2] refers to env[key1].
  1610. Throws an Exception in case of dependency cycles.
  1611. """
  1612. # Since environment variables can refer to other variables, the evaluation
  1613. # order is important. Below is the logic to compute the dependency graph
  1614. # and sort it.
  1615. regex = re.compile(r"\$\{([a-zA-Z0-9\-_]+)\}")
  1616. def GetEdges(node):
  1617. # Use a definition of edges such that user_of_variable -> used_variable.
  1618. # This happens to be easier in this case, since a variable's
  1619. # definition contains all variables it references in a single string.
  1620. # We can then reverse the result of the topological sort at the end.
  1621. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
  1622. matches = {v for v in regex.findall(env[node]) if v in env}
  1623. for dependee in matches:
  1624. assert "${" not in dependee, "Nested variables not supported: " + dependee
  1625. return matches
  1626. try:
  1627. # Topologically sort, and then reverse, because we used an edge definition
  1628. # that's inverted from the expected result of this function (see comment
  1629. # above).
  1630. order = gyp.common.TopologicallySorted(env.keys(), GetEdges)
  1631. order.reverse()
  1632. return order
  1633. except gyp.common.CycleError as e:
  1634. raise GypError(
  1635. "Xcode environment variables are cyclically dependent: " + str(e.nodes)
  1636. )
  1637. def GetSortedXcodeEnv(
  1638. xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None
  1639. ):
  1640. env = _GetXcodeEnv(
  1641. xcode_settings, built_products_dir, srcroot, configuration, additional_settings
  1642. )
  1643. return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)]
  1644. def GetSpecPostbuildCommands(spec, quiet=False):
  1645. """Returns the list of postbuilds explicitly defined on |spec|, in a form
  1646. executable by a shell."""
  1647. postbuilds = []
  1648. for postbuild in spec.get("postbuilds", []):
  1649. if not quiet:
  1650. postbuilds.append(
  1651. "echo POSTBUILD\\(%s\\) %s"
  1652. % (spec["target_name"], postbuild["postbuild_name"])
  1653. )
  1654. postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild["action"]))
  1655. return postbuilds
  1656. def _HasIOSTarget(targets):
  1657. """Returns true if any target contains the iOS specific key
  1658. IPHONEOS_DEPLOYMENT_TARGET."""
  1659. for target_dict in targets.values():
  1660. for config in target_dict["configurations"].values():
  1661. if config.get("xcode_settings", {}).get("IPHONEOS_DEPLOYMENT_TARGET"):
  1662. return True
  1663. return False
  1664. def _AddIOSDeviceConfigurations(targets):
  1665. """Clone all targets and append -iphoneos to the name. Configure these targets
  1666. to build for iOS devices and use correct architectures for those builds."""
  1667. for target_dict in targets.values():
  1668. toolset = target_dict["toolset"]
  1669. configs = target_dict["configurations"]
  1670. for config_name, simulator_config_dict in dict(configs).items():
  1671. iphoneos_config_dict = copy.deepcopy(simulator_config_dict)
  1672. configs[config_name + "-iphoneos"] = iphoneos_config_dict
  1673. configs[config_name + "-iphonesimulator"] = simulator_config_dict
  1674. if toolset == "target":
  1675. simulator_config_dict["xcode_settings"]["SDKROOT"] = "iphonesimulator"
  1676. iphoneos_config_dict["xcode_settings"]["SDKROOT"] = "iphoneos"
  1677. return targets
  1678. def CloneConfigurationForDeviceAndEmulator(target_dicts):
  1679. """If |target_dicts| contains any iOS targets, automatically create -iphoneos
  1680. targets for iOS device builds."""
  1681. if _HasIOSTarget(target_dicts):
  1682. return _AddIOSDeviceConfigurations(target_dicts)
  1683. return target_dicts