gyp-mac-tool 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. #!/usr/bin/env python3
  2. # Generated by gyp. Do not edit.
  3. # Copyright (c) 2012 Google Inc. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """Utility functions to perform Xcode-style build steps.
  7. These functions are executed via gyp-mac-tool when using the Makefile generator.
  8. """
  9. import fcntl
  10. import fnmatch
  11. import glob
  12. import json
  13. import os
  14. import plistlib
  15. import re
  16. import shutil
  17. import struct
  18. import subprocess
  19. import sys
  20. import tempfile
  21. def main(args):
  22. executor = MacTool()
  23. exit_code = executor.Dispatch(args)
  24. if exit_code is not None:
  25. sys.exit(exit_code)
  26. class MacTool:
  27. """This class performs all the Mac tooling steps. The methods can either be
  28. executed directly, or dispatched from an argument list."""
  29. def Dispatch(self, args):
  30. """Dispatches a string command to a method."""
  31. if len(args) < 1:
  32. raise Exception("Not enough arguments")
  33. method = "Exec%s" % self._CommandifyName(args[0])
  34. return getattr(self, method)(*args[1:])
  35. def _CommandifyName(self, name_string):
  36. """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
  37. return name_string.title().replace("-", "")
  38. def ExecCopyBundleResource(self, source, dest, convert_to_binary):
  39. """Copies a resource file to the bundle/Resources directory, performing any
  40. necessary compilation on each resource."""
  41. convert_to_binary = convert_to_binary == "True"
  42. extension = os.path.splitext(source)[1].lower()
  43. if os.path.isdir(source):
  44. # Copy tree.
  45. # TODO(thakis): This copies file attributes like mtime, while the
  46. # single-file branch below doesn't. This should probably be changed to
  47. # be consistent with the single-file branch.
  48. if os.path.exists(dest):
  49. shutil.rmtree(dest)
  50. shutil.copytree(source, dest)
  51. elif extension in {".xib", ".storyboard"}:
  52. return self._CopyXIBFile(source, dest)
  53. elif extension == ".strings" and not convert_to_binary:
  54. self._CopyStringsFile(source, dest)
  55. else:
  56. if os.path.exists(dest):
  57. os.unlink(dest)
  58. shutil.copy(source, dest)
  59. if convert_to_binary and extension in {".plist", ".strings"}:
  60. self._ConvertToBinary(dest)
  61. def _CopyXIBFile(self, source, dest):
  62. """Compiles a XIB file with ibtool into a binary plist in the bundle."""
  63. # ibtool sometimes crashes with relative paths. See crbug.com/314728.
  64. base = os.path.dirname(os.path.realpath(__file__))
  65. if os.path.relpath(source):
  66. source = os.path.join(base, source)
  67. if os.path.relpath(dest):
  68. dest = os.path.join(base, dest)
  69. args = ["xcrun", "ibtool", "--errors", "--warnings", "--notices"]
  70. if os.environ["XCODE_VERSION_ACTUAL"] > "0700":
  71. args.extend(["--auto-activate-custom-fonts"])
  72. if "IPHONEOS_DEPLOYMENT_TARGET" in os.environ:
  73. args.extend(
  74. [
  75. "--target-device",
  76. "iphone",
  77. "--target-device",
  78. "ipad",
  79. "--minimum-deployment-target",
  80. os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
  81. ]
  82. )
  83. else:
  84. args.extend(
  85. [
  86. "--target-device",
  87. "mac",
  88. "--minimum-deployment-target",
  89. os.environ["MACOSX_DEPLOYMENT_TARGET"],
  90. ]
  91. )
  92. args.extend(
  93. ["--output-format", "human-readable-text", "--compile", dest, source]
  94. )
  95. ibtool_section_re = re.compile(r"/\*.*\*/")
  96. ibtool_re = re.compile(r".*note:.*is clipping its content")
  97. try:
  98. stdout = subprocess.check_output(args)
  99. except subprocess.CalledProcessError as e:
  100. print(e.output)
  101. raise
  102. current_section_header = None
  103. for line in stdout.splitlines():
  104. if ibtool_section_re.match(line):
  105. current_section_header = line
  106. elif not ibtool_re.match(line):
  107. if current_section_header:
  108. print(current_section_header)
  109. current_section_header = None
  110. print(line)
  111. return 0
  112. def _ConvertToBinary(self, dest):
  113. subprocess.check_call(
  114. ["xcrun", "plutil", "-convert", "binary1", "-o", dest, dest]
  115. )
  116. def _CopyStringsFile(self, source, dest):
  117. """Copies a .strings file using iconv to reconvert the input into UTF-16."""
  118. input_code = self._DetectInputEncoding(source) or "UTF-8"
  119. # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
  120. # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
  121. # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
  122. # semicolon in dictionary.
  123. # on invalid files. Do the same kind of validation.
  124. import CoreFoundation
  125. with open(source, "rb") as in_file:
  126. s = in_file.read()
  127. d = CoreFoundation.CFDataCreate(None, s, len(s))
  128. _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
  129. if error:
  130. return
  131. with open(dest, "wb") as fp:
  132. fp.write(s.decode(input_code).encode("UTF-16"))
  133. def _DetectInputEncoding(self, file_name):
  134. """Reads the first few bytes from file_name and tries to guess the text
  135. encoding. Returns None as a guess if it can't detect it."""
  136. with open(file_name, "rb") as fp:
  137. try:
  138. header = fp.read(3)
  139. except Exception:
  140. return None
  141. if header.startswith((b"\xFE\xFF", b"\xFF\xFE")):
  142. return "UTF-16"
  143. elif header.startswith(b"\xEF\xBB\xBF"):
  144. return "UTF-8"
  145. else:
  146. return None
  147. def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
  148. """Copies the |source| Info.plist to the destination directory |dest|."""
  149. # Read the source Info.plist into memory.
  150. with open(source) as fd:
  151. lines = fd.read()
  152. # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
  153. plist = plistlib.readPlistFromString(lines)
  154. if keys:
  155. plist.update(json.loads(keys[0]))
  156. lines = plistlib.writePlistToString(plist)
  157. # Go through all the environment variables and replace them as variables in
  158. # the file.
  159. IDENT_RE = re.compile(r"[_/\s]")
  160. for key in os.environ:
  161. if key.startswith("_"):
  162. continue
  163. evar = "${%s}" % key
  164. evalue = os.environ[key]
  165. lines = lines.replace(lines, evar, evalue)
  166. # Xcode supports various suffices on environment variables, which are
  167. # all undocumented. :rfc1034identifier is used in the standard project
  168. # template these days, and :identifier was used earlier. They are used to
  169. # convert non-url characters into things that look like valid urls --
  170. # except that the replacement character for :identifier, '_' isn't valid
  171. # in a URL either -- oops, hence :rfc1034identifier was born.
  172. evar = "${%s:identifier}" % key
  173. evalue = IDENT_RE.sub("_", os.environ[key])
  174. lines = lines.replace(lines, evar, evalue)
  175. evar = "${%s:rfc1034identifier}" % key
  176. evalue = IDENT_RE.sub("-", os.environ[key])
  177. lines = lines.replace(lines, evar, evalue)
  178. # Remove any keys with values that haven't been replaced.
  179. lines = lines.splitlines()
  180. for i in range(len(lines)):
  181. if lines[i].strip().startswith("<string>${"):
  182. lines[i] = None
  183. lines[i - 1] = None
  184. lines = "\n".join(line for line in lines if line is not None)
  185. # Write out the file with variables replaced.
  186. with open(dest, "w") as fd:
  187. fd.write(lines)
  188. # Now write out PkgInfo file now that the Info.plist file has been
  189. # "compiled".
  190. self._WritePkgInfo(dest)
  191. if convert_to_binary == "True":
  192. self._ConvertToBinary(dest)
  193. def _WritePkgInfo(self, info_plist):
  194. """This writes the PkgInfo file from the data stored in Info.plist."""
  195. plist = plistlib.readPlist(info_plist)
  196. if not plist:
  197. return
  198. # Only create PkgInfo for executable types.
  199. package_type = plist["CFBundlePackageType"]
  200. if package_type != "APPL":
  201. return
  202. # The format of PkgInfo is eight characters, representing the bundle type
  203. # and bundle signature, each four characters. If that is missing, four
  204. # '?' characters are used instead.
  205. signature_code = plist.get("CFBundleSignature", "????")
  206. if len(signature_code) != 4: # Wrong length resets everything, too.
  207. signature_code = "?" * 4
  208. dest = os.path.join(os.path.dirname(info_plist), "PkgInfo")
  209. with open(dest, "w") as fp:
  210. fp.write(f"{package_type}{signature_code}")
  211. def ExecFlock(self, lockfile, *cmd_list):
  212. """Emulates the most basic behavior of Linux's flock(1)."""
  213. # Rely on exception handling to report errors.
  214. fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666)
  215. fcntl.flock(fd, fcntl.LOCK_EX)
  216. return subprocess.call(cmd_list)
  217. def ExecFilterLibtool(self, *cmd_list):
  218. """Calls libtool and filters out '/path/to/libtool: file: foo.o has no
  219. symbols'."""
  220. libtool_re = re.compile(
  221. r"^.*libtool: (?:for architecture: \S* )?file: .* has no symbols$"
  222. )
  223. libtool_re5 = re.compile(
  224. r"^.*libtool: warning for library: "
  225. + r".* the table of contents is empty "
  226. + r"\(no object file members in the library define global symbols\)$"
  227. )
  228. env = os.environ.copy()
  229. # Ref:
  230. # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
  231. # The problem with this flag is that it resets the file mtime on the file to
  232. # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
  233. env["ZERO_AR_DATE"] = "1"
  234. libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
  235. err = libtoolout.communicate()[1].decode("utf-8")
  236. for line in err.splitlines():
  237. if not libtool_re.match(line) and not libtool_re5.match(line):
  238. print(line, file=sys.stderr)
  239. # Unconditionally touch the output .a file on the command line if present
  240. # and the command succeeded. A bit hacky.
  241. if not libtoolout.returncode:
  242. for i in range(len(cmd_list) - 1):
  243. if cmd_list[i] == "-o" and cmd_list[i + 1].endswith(".a"):
  244. os.utime(cmd_list[i + 1], None)
  245. break
  246. return libtoolout.returncode
  247. def ExecPackageIosFramework(self, framework):
  248. # Find the name of the binary based on the part before the ".framework".
  249. binary = os.path.basename(framework).split(".")[0]
  250. module_path = os.path.join(framework, "Modules")
  251. if not os.path.exists(module_path):
  252. os.mkdir(module_path)
  253. module_template = (
  254. "framework module %s {\n"
  255. ' umbrella header "%s.h"\n'
  256. "\n"
  257. " export *\n"
  258. " module * { export * }\n"
  259. "}\n" % (binary, binary)
  260. )
  261. with open(os.path.join(module_path, "module.modulemap"), "w") as module_file:
  262. module_file.write(module_template)
  263. def ExecPackageFramework(self, framework, version):
  264. """Takes a path to Something.framework and the Current version of that and
  265. sets up all the symlinks."""
  266. # Find the name of the binary based on the part before the ".framework".
  267. binary = os.path.basename(framework).split(".")[0]
  268. CURRENT = "Current"
  269. RESOURCES = "Resources"
  270. VERSIONS = "Versions"
  271. if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
  272. # Binary-less frameworks don't seem to contain symlinks (see e.g.
  273. # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
  274. return
  275. # Move into the framework directory to set the symlinks correctly.
  276. pwd = os.getcwd()
  277. os.chdir(framework)
  278. # Set up the Current version.
  279. self._Relink(version, os.path.join(VERSIONS, CURRENT))
  280. # Set up the root symlinks.
  281. self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
  282. self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
  283. # Back to where we were before!
  284. os.chdir(pwd)
  285. def _Relink(self, dest, link):
  286. """Creates a symlink to |dest| named |link|. If |link| already exists,
  287. it is overwritten."""
  288. if os.path.lexists(link):
  289. os.remove(link)
  290. os.symlink(dest, link)
  291. def ExecCompileIosFrameworkHeaderMap(self, out, framework, *all_headers):
  292. framework_name = os.path.basename(framework).split(".")[0]
  293. all_headers = [os.path.abspath(header) for header in all_headers]
  294. filelist = {}
  295. for header in all_headers:
  296. filename = os.path.basename(header)
  297. filelist[filename] = header
  298. filelist[os.path.join(framework_name, filename)] = header
  299. WriteHmap(out, filelist)
  300. def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers):
  301. header_path = os.path.join(framework, "Headers")
  302. if not os.path.exists(header_path):
  303. os.makedirs(header_path)
  304. for header in copy_headers:
  305. shutil.copy(header, os.path.join(header_path, os.path.basename(header)))
  306. def ExecCompileXcassets(self, keys, *inputs):
  307. """Compiles multiple .xcassets files into a single .car file.
  308. This invokes 'actool' to compile all the inputs .xcassets files. The
  309. |keys| arguments is a json-encoded dictionary of extra arguments to
  310. pass to 'actool' when the asset catalogs contains an application icon
  311. or a launch image.
  312. Note that 'actool' does not create the Assets.car file if the asset
  313. catalogs does not contains imageset.
  314. """
  315. command_line = [
  316. "xcrun",
  317. "actool",
  318. "--output-format",
  319. "human-readable-text",
  320. "--compress-pngs",
  321. "--notices",
  322. "--warnings",
  323. "--errors",
  324. ]
  325. is_iphone_target = "IPHONEOS_DEPLOYMENT_TARGET" in os.environ
  326. if is_iphone_target:
  327. platform = os.environ["CONFIGURATION"].split("-")[-1]
  328. if platform not in ("iphoneos", "iphonesimulator"):
  329. platform = "iphonesimulator"
  330. command_line.extend(
  331. [
  332. "--platform",
  333. platform,
  334. "--target-device",
  335. "iphone",
  336. "--target-device",
  337. "ipad",
  338. "--minimum-deployment-target",
  339. os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
  340. "--compile",
  341. os.path.abspath(os.environ["CONTENTS_FOLDER_PATH"]),
  342. ]
  343. )
  344. else:
  345. command_line.extend(
  346. [
  347. "--platform",
  348. "macosx",
  349. "--target-device",
  350. "mac",
  351. "--minimum-deployment-target",
  352. os.environ["MACOSX_DEPLOYMENT_TARGET"],
  353. "--compile",
  354. os.path.abspath(os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]),
  355. ]
  356. )
  357. if keys:
  358. keys = json.loads(keys)
  359. for key, value in keys.items():
  360. arg_name = "--" + key
  361. if isinstance(value, bool):
  362. if value:
  363. command_line.append(arg_name)
  364. elif isinstance(value, list):
  365. for v in value:
  366. command_line.append(arg_name)
  367. command_line.append(str(v))
  368. else:
  369. command_line.append(arg_name)
  370. command_line.append(str(value))
  371. # Note: actool crashes if inputs path are relative, so use os.path.abspath
  372. # to get absolute path name for inputs.
  373. command_line.extend(map(os.path.abspath, inputs))
  374. subprocess.check_call(command_line)
  375. def ExecMergeInfoPlist(self, output, *inputs):
  376. """Merge multiple .plist files into a single .plist file."""
  377. merged_plist = {}
  378. for path in inputs:
  379. plist = self._LoadPlistMaybeBinary(path)
  380. self._MergePlist(merged_plist, plist)
  381. plistlib.writePlist(merged_plist, output)
  382. def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve):
  383. """Code sign a bundle.
  384. This function tries to code sign an iOS bundle, following the same
  385. algorithm as Xcode:
  386. 1. pick the provisioning profile that best match the bundle identifier,
  387. and copy it into the bundle as embedded.mobileprovision,
  388. 2. copy Entitlements.plist from user or SDK next to the bundle,
  389. 3. code sign the bundle.
  390. """
  391. substitutions, overrides = self._InstallProvisioningProfile(
  392. provisioning, self._GetCFBundleIdentifier()
  393. )
  394. entitlements_path = self._InstallEntitlements(
  395. entitlements, substitutions, overrides
  396. )
  397. args = ["codesign", "--force", "--sign", key]
  398. if preserve == "True":
  399. args.extend(["--deep", "--preserve-metadata=identifier,entitlements"])
  400. else:
  401. args.extend(["--entitlements", entitlements_path])
  402. args.extend(["--timestamp=none", path])
  403. subprocess.check_call(args)
  404. def _InstallProvisioningProfile(self, profile, bundle_identifier):
  405. """Installs embedded.mobileprovision into the bundle.
  406. Args:
  407. profile: string, optional, short name of the .mobileprovision file
  408. to use, if empty or the file is missing, the best file installed
  409. will be used
  410. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  411. Returns:
  412. A tuple containing two dictionary: variables substitutions and values
  413. to overrides when generating the entitlements file.
  414. """
  415. source_path, provisioning_data, team_id = self._FindProvisioningProfile(
  416. profile, bundle_identifier
  417. )
  418. target_path = os.path.join(
  419. os.environ["BUILT_PRODUCTS_DIR"],
  420. os.environ["CONTENTS_FOLDER_PATH"],
  421. "embedded.mobileprovision",
  422. )
  423. shutil.copy2(source_path, target_path)
  424. substitutions = self._GetSubstitutions(bundle_identifier, team_id + ".")
  425. return substitutions, provisioning_data["Entitlements"]
  426. def _FindProvisioningProfile(self, profile, bundle_identifier):
  427. """Finds the .mobileprovision file to use for signing the bundle.
  428. Checks all the installed provisioning profiles (or if the user specified
  429. the PROVISIONING_PROFILE variable, only consult it) and select the most
  430. specific that correspond to the bundle identifier.
  431. Args:
  432. profile: string, optional, short name of the .mobileprovision file
  433. to use, if empty or the file is missing, the best file installed
  434. will be used
  435. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  436. Returns:
  437. A tuple of the path to the selected provisioning profile, the data of
  438. the embedded plist in the provisioning profile and the team identifier
  439. to use for code signing.
  440. Raises:
  441. SystemExit: if no .mobileprovision can be used to sign the bundle.
  442. """
  443. profiles_dir = os.path.join(
  444. os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles"
  445. )
  446. if not os.path.isdir(profiles_dir):
  447. print(
  448. "cannot find mobile provisioning for %s" % (bundle_identifier),
  449. file=sys.stderr,
  450. )
  451. sys.exit(1)
  452. provisioning_profiles = None
  453. if profile:
  454. profile_path = os.path.join(profiles_dir, profile + ".mobileprovision")
  455. if os.path.exists(profile_path):
  456. provisioning_profiles = [profile_path]
  457. if not provisioning_profiles:
  458. provisioning_profiles = glob.glob(
  459. os.path.join(profiles_dir, "*.mobileprovision")
  460. )
  461. valid_provisioning_profiles = {}
  462. for profile_path in provisioning_profiles:
  463. profile_data = self._LoadProvisioningProfile(profile_path)
  464. app_id_pattern = profile_data.get("Entitlements", {}).get(
  465. "application-identifier", ""
  466. )
  467. for team_identifier in profile_data.get("TeamIdentifier", []):
  468. app_id = f"{team_identifier}.{bundle_identifier}"
  469. if fnmatch.fnmatch(app_id, app_id_pattern):
  470. valid_provisioning_profiles[app_id_pattern] = (
  471. profile_path,
  472. profile_data,
  473. team_identifier,
  474. )
  475. if not valid_provisioning_profiles:
  476. print(
  477. "cannot find mobile provisioning for %s" % (bundle_identifier),
  478. file=sys.stderr,
  479. )
  480. sys.exit(1)
  481. # If the user has multiple provisioning profiles installed that can be
  482. # used for ${bundle_identifier}, pick the most specific one (ie. the
  483. # provisioning profile whose pattern is the longest).
  484. selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
  485. return valid_provisioning_profiles[selected_key]
  486. def _LoadProvisioningProfile(self, profile_path):
  487. """Extracts the plist embedded in a provisioning profile.
  488. Args:
  489. profile_path: string, path to the .mobileprovision file
  490. Returns:
  491. Content of the plist embedded in the provisioning profile as a dictionary.
  492. """
  493. with tempfile.NamedTemporaryFile() as temp:
  494. subprocess.check_call(
  495. ["security", "cms", "-D", "-i", profile_path, "-o", temp.name]
  496. )
  497. return self._LoadPlistMaybeBinary(temp.name)
  498. def _MergePlist(self, merged_plist, plist):
  499. """Merge |plist| into |merged_plist|."""
  500. for key, value in plist.items():
  501. if isinstance(value, dict):
  502. merged_value = merged_plist.get(key, {})
  503. if isinstance(merged_value, dict):
  504. self._MergePlist(merged_value, value)
  505. merged_plist[key] = merged_value
  506. else:
  507. merged_plist[key] = value
  508. else:
  509. merged_plist[key] = value
  510. def _LoadPlistMaybeBinary(self, plist_path):
  511. """Loads into a memory a plist possibly encoded in binary format.
  512. This is a wrapper around plistlib.readPlist that tries to convert the
  513. plist to the XML format if it can't be parsed (assuming that it is in
  514. the binary format).
  515. Args:
  516. plist_path: string, path to a plist file, in XML or binary format
  517. Returns:
  518. Content of the plist as a dictionary.
  519. """
  520. try:
  521. # First, try to read the file using plistlib that only supports XML,
  522. # and if an exception is raised, convert a temporary copy to XML and
  523. # load that copy.
  524. return plistlib.readPlist(plist_path)
  525. except Exception:
  526. pass
  527. with tempfile.NamedTemporaryFile() as temp:
  528. shutil.copy2(plist_path, temp.name)
  529. subprocess.check_call(["plutil", "-convert", "xml1", temp.name])
  530. return plistlib.readPlist(temp.name)
  531. def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
  532. """Constructs a dictionary of variable substitutions for Entitlements.plist.
  533. Args:
  534. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  535. app_identifier_prefix: string, value for AppIdentifierPrefix
  536. Returns:
  537. Dictionary of substitutions to apply when generating Entitlements.plist.
  538. """
  539. return {
  540. "CFBundleIdentifier": bundle_identifier,
  541. "AppIdentifierPrefix": app_identifier_prefix,
  542. }
  543. def _GetCFBundleIdentifier(self):
  544. """Extracts CFBundleIdentifier value from Info.plist in the bundle.
  545. Returns:
  546. Value of CFBundleIdentifier in the Info.plist located in the bundle.
  547. """
  548. info_plist_path = os.path.join(
  549. os.environ["TARGET_BUILD_DIR"], os.environ["INFOPLIST_PATH"]
  550. )
  551. info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
  552. return info_plist_data["CFBundleIdentifier"]
  553. def _InstallEntitlements(self, entitlements, substitutions, overrides):
  554. """Generates and install the ${BundleName}.xcent entitlements file.
  555. Expands variables "$(variable)" pattern in the source entitlements file,
  556. add extra entitlements defined in the .mobileprovision file and the copy
  557. the generated plist to "${BundlePath}.xcent".
  558. Args:
  559. entitlements: string, optional, path to the Entitlements.plist template
  560. to use, defaults to "${SDKROOT}/Entitlements.plist"
  561. substitutions: dictionary, variable substitutions
  562. overrides: dictionary, values to add to the entitlements
  563. Returns:
  564. Path to the generated entitlements file.
  565. """
  566. source_path = entitlements
  567. target_path = os.path.join(
  568. os.environ["BUILT_PRODUCTS_DIR"], os.environ["PRODUCT_NAME"] + ".xcent"
  569. )
  570. if not source_path:
  571. source_path = os.path.join(os.environ["SDKROOT"], "Entitlements.plist")
  572. shutil.copy2(source_path, target_path)
  573. data = self._LoadPlistMaybeBinary(target_path)
  574. data = self._ExpandVariables(data, substitutions)
  575. if overrides:
  576. for key in overrides:
  577. if key not in data:
  578. data[key] = overrides[key]
  579. plistlib.writePlist(data, target_path)
  580. return target_path
  581. def _ExpandVariables(self, data, substitutions):
  582. """Expands variables "$(variable)" in data.
  583. Args:
  584. data: object, can be either string, list or dictionary
  585. substitutions: dictionary, variable substitutions to perform
  586. Returns:
  587. Copy of data where each references to "$(variable)" has been replaced
  588. by the corresponding value found in substitutions, or left intact if
  589. the key was not found.
  590. """
  591. if isinstance(data, str):
  592. for key, value in substitutions.items():
  593. data = data.replace("$(%s)" % key, value)
  594. return data
  595. if isinstance(data, list):
  596. return [self._ExpandVariables(v, substitutions) for v in data]
  597. if isinstance(data, dict):
  598. return {k: self._ExpandVariables(data[k], substitutions) for k in data}
  599. return data
  600. def NextGreaterPowerOf2(x):
  601. return 2 ** (x).bit_length()
  602. def WriteHmap(output_name, filelist):
  603. """Generates a header map based on |filelist|.
  604. Per Mark Mentovai:
  605. A header map is structured essentially as a hash table, keyed by names used
  606. in #includes, and providing pathnames to the actual files.
  607. The implementation below and the comment above comes from inspecting:
  608. http://www.opensource.apple.com/source/distcc/distcc-2503/distcc_dist/include_server/headermap.py?txt
  609. while also looking at the implementation in clang in:
  610. https://llvm.org/svn/llvm-project/cfe/trunk/lib/Lex/HeaderMap.cpp
  611. """
  612. magic = 1751998832
  613. version = 1
  614. _reserved = 0
  615. count = len(filelist)
  616. capacity = NextGreaterPowerOf2(count)
  617. strings_offset = 24 + (12 * capacity)
  618. max_value_length = max(len(value) for value in filelist.values())
  619. out = open(output_name, "wb")
  620. out.write(
  621. struct.pack(
  622. "<LHHLLLL",
  623. magic,
  624. version,
  625. _reserved,
  626. strings_offset,
  627. count,
  628. capacity,
  629. max_value_length,
  630. )
  631. )
  632. # Create empty hashmap buckets.
  633. buckets = [None] * capacity
  634. for file, path in filelist.items():
  635. key = 0
  636. for c in file:
  637. key += ord(c.lower()) * 13
  638. # Fill next empty bucket.
  639. while buckets[key & capacity - 1] is not None:
  640. key = key + 1
  641. buckets[key & capacity - 1] = (file, path)
  642. next_offset = 1
  643. for bucket in buckets:
  644. if bucket is None:
  645. out.write(struct.pack("<LLL", 0, 0, 0))
  646. else:
  647. (file, path) = bucket
  648. key_offset = next_offset
  649. prefix_offset = key_offset + len(file) + 1
  650. suffix_offset = prefix_offset + len(os.path.dirname(path) + os.sep) + 1
  651. next_offset = suffix_offset + len(os.path.basename(path)) + 1
  652. out.write(struct.pack("<LLL", key_offset, prefix_offset, suffix_offset))
  653. # Pad byte since next offset starts at 1.
  654. out.write(struct.pack("<x"))
  655. for bucket in buckets:
  656. if bucket is not None:
  657. (file, path) = bucket
  658. out.write(struct.pack("<%ds" % len(file), file))
  659. out.write(struct.pack("<s", "\0"))
  660. base = os.path.dirname(path) + os.sep
  661. out.write(struct.pack("<%ds" % len(base), base))
  662. out.write(struct.pack("<s", "\0"))
  663. path = os.path.basename(path)
  664. out.write(struct.pack("<%ds" % len(path), path))
  665. out.write(struct.pack("<s", "\0"))
  666. if __name__ == "__main__":
  667. sys.exit(main(sys.argv[1:]))