5dd3bea1b4663d2a8f74b6982cb57c82283f43117efe704efc6823a961625b13f7bc8ecaeb46a47e5e8afbae7c22c4cbc355a5b8a137593002fa0645418e63 30 KB

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