gyp-mac-tool 30 KB

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