Fix sample iOS project to work on macOS Monterey and M1 macs

Only python3 is available on macOS Monterey, so convert the sample
project to use python3 to work on new version of macOS.

Add an additional `target_environment` gn variable to control if
the build is a device or simulator build. This is needed to build
for simulator on an M1 mac (where the cpu is identified as `arm64`).

Bug: none
Change-Id: Ibc9ffff24ac5c1e5991c19d7c34ca2c2a95a757e
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/14140
Reviewed-by: Brett Wilson <brettw@chromium.org>
Commit-Queue: Sylvain Defresne <sdefresne@chromium.org>
diff --git a/examples/ios/.gn b/examples/ios/.gn
index e5b6d4a..fc31273 100644
--- a/examples/ios/.gn
+++ b/examples/ios/.gn
@@ -1,2 +1,6 @@
 # The location of the build configuration file.
 buildconfig = "//build/BUILDCONFIG.gn"
+
+# The build script are using `python3` which is the only version of
+# python installed by default on macOS Monterey and above.
+script_executable = "python3"
diff --git a/examples/ios/build/BUILD.gn b/examples/ios/build/BUILD.gn
index b6bb6de..e543493 100644
--- a/examples/ios/build/BUILD.gn
+++ b/examples/ios/build/BUILD.gn
@@ -77,6 +77,8 @@
                           [
                             "--target-cpu",
                             current_cpu,
+                            "--target-environment",
+                            target_environment,
                             "--deployment-target",
                             ios_deployment_target,
                           ],
diff --git a/examples/ios/build/BUILDCONFIG.gn b/examples/ios/build/BUILDCONFIG.gn
index 53ee3d9..ca6c49d 100644
--- a/examples/ios/build/BUILDCONFIG.gn
+++ b/examples/ios/build/BUILDCONFIG.gn
@@ -15,6 +15,16 @@
   current_os = target_os
 }
 
+declare_args() {
+  # Control which platform the build is targeting. Valid values are
+  # "simulator" or "device".
+  target_environment = "simulator"
+}
+
+assert(
+    target_environment == "simulator" || target_environment == "device",
+    "Only supported values for target_environment are 'simulator' and 'device'")
+
 # All binary targets will get this list of configs by default.
 _shared_binary_target_configs = [ "//build:compiler" ]
 
diff --git a/examples/ios/build/config/ios/scripts/find_app_identifier_prefix.py b/examples/ios/build/config/ios/scripts/find_app_identifier_prefix.py
index cf38b10..9e1dfbc 100644
--- a/examples/ios/build/config/ios/scripts/find_app_identifier_prefix.py
+++ b/examples/ios/build/config/ios/scripts/find_app_identifier_prefix.py
@@ -21,7 +21,7 @@
 
   def __init__(self, mobileprovision_path):
     self._path = mobileprovision_path
-    self._data = plistlib.readPlistFromString(
+    self._data = plistlib.loads(
         subprocess.check_output(
             ['security', 'cms', '-D', '-i', mobileprovision_path]))
 
diff --git a/examples/ios/build/config/ios/scripts/merge_plist.py b/examples/ios/build/config/ios/scripts/merge_plist.py
index 452cf53..f13ce00 100644
--- a/examples/ios/build/config/ios/scripts/merge_plist.py
+++ b/examples/ios/build/config/ios/scripts/merge_plist.py
@@ -18,11 +18,15 @@
 VARIABLE_PATTERN = re.compile(r'\$\(([^)]*)\)')
 
 
+def GetCommandOutput(command):
+  """Returns the output of `command` as a string."""
+  return subprocess.check_output(command, encoding='utf-8')
+
+
 def LoadPlist(plist_path):
   """Loads Apple Property List file at |plist_path|."""
   return json.loads(
-      subprocess.check_output(
-          ['plutil', '-convert', 'json', '-o', '-', plist_path]))
+      GetCommandOutput(['plutil', '-convert', 'json', '-o', '-', plist_path]))
 
 
 def SavePlist(plist_path, content, format):
@@ -30,7 +34,7 @@
   proc = subprocess.Popen(
       ['plutil', '-convert', format, '-o', plist_path, '-'],
       stdin=subprocess.PIPE)
-  output, _ = proc.communicate(json.dumps(content))
+  output, _ = proc.communicate(json.dumps(content).encode('utf-8'))
   if proc.returncode:
     raise subprocess.CalledProcessError(
         proc.returncode,
@@ -76,7 +80,7 @@
   if isinstance(plist, list):
     return [ PerformSubstitutions(item, substitutions) for item in plist ]
 
-  if isinstance(plist, (str, unicode)):
+  if isinstance(plist, str):
     result = plist
     while True:
       match = VARIABLE_PATTERN.search(result)
diff --git a/examples/ios/build/config/ios/scripts/sdk_info.py b/examples/ios/build/config/ios/scripts/sdk_info.py
index 831a3ed..c8f55cb 100644
--- a/examples/ios/build/config/ios/scripts/sdk_info.py
+++ b/examples/ios/build/config/ios/scripts/sdk_info.py
@@ -16,6 +16,11 @@
 XCODE_BUILD_PATTERN = re.compile(r'Build version (.*)')
 
 
+def GetCommandOutput(command):
+  """Returns the output of `command` as a string."""
+  return subprocess.check_output(command, encoding='utf-8')
+
+
 def GetAppleCpuName(target_cpu):
   """Returns the name of the |target_cpu| using Apple's convention."""
   return {
@@ -25,36 +30,31 @@
   }.get(target_cpu, target_cpu)
 
 
-def IsSimulator(target_cpu):
-  """Returns whether the |target_cpu| corresponds to a simulator build."""
-  return not target_cpu.startswith('arm')
+def GetPlatform(target_environment):
+  """Returns the platform for |target_environment|."""
+  return {
+      'simulator': 'iphonesimulator',
+      'device': 'iphoneos'
+  }[target_environment]
 
 
-def GetPlatform(target_cpu):
-  """Returns the platform for the |target_cpu|."""
-  if IsSimulator(target_cpu):
-    return 'iphonesimulator'
-  else:
-    return 'iphoneos'
-
-
-def GetPlaformDisplayName(target_cpu):
-  """Returns the platform display name for the |target_cpu|."""
-  if IsSimulator(target_cpu):
-    return 'iPhoneSimulator'
-  else:
-    return 'iPhoneOS'
+def GetPlaformDisplayName(target_environment):
+  """Returns the platform display name for |target_environment|."""
+  return {
+      'simulator': 'iPhoneSimulator',
+      'device': 'iPhoneOS'
+  }[target_environment]
 
 
 def ExtractOSVersion():
   """Extract the version of macOS of the current machine."""
-  return subprocess.check_output(['sw_vers', '-buildVersion']).strip()
+  return GetCommandOutput(['sw_vers', '-buildVersion']).strip()
 
 
 def ExtractXcodeInfo():
   """Extract Xcode version and build version."""
   version, build = None, None
-  for line in subprocess.check_output(['xcodebuild', '-version']).splitlines():
+  for line in GetCommandOutput(['xcodebuild', '-version']).splitlines():
     match = XCODE_VERSION_PATTERN.search(line)
     if match:
       major, minor = match.group(1), match.group(2)
@@ -72,23 +72,22 @@
 
 def ExtractSDKInfo(info, sdk):
   """Extract information about the SDK."""
-  return subprocess.check_output(
-      ['xcrun', '--sdk', sdk, '--show-sdk-' + info]).strip()
+  return GetCommandOutput(['xcrun', '--sdk', sdk, '--show-sdk-' + info]).strip()
 
 
 def GetDeveloperDir():
   """Returns the developer dir."""
-  return subprocess.check_output(['xcode-select', '-print-path']).strip()
+  return GetCommandOutput(['xcode-select', '-print-path']).strip()
 
 
-def GetSDKInfoForCpu(target_cpu, sdk_version, deployment_target):
+def GetSDKInfoForCpu(target_cpu, environment, sdk_version, deployment_target):
   """Returns a dictionary with information about the SDK."""
-  platform = GetPlatform(target_cpu)
+  platform = GetPlatform(environment)
   sdk_version = sdk_version or ExtractSDKInfo('version', platform)
   deployment_target = deployment_target or sdk_version
 
   target = target_cpu + '-apple-ios' + deployment_target
-  if IsSimulator(target_cpu):
+  if environment == 'simulator':
     target = target + '-simulator'
 
   xcode_version, xcode_build = ExtractXcodeInfo()
@@ -96,10 +95,10 @@
 
   sdk_info = {}
   sdk_info['compiler'] = 'com.apple.compilers.llvm.clang.1_0'
-  sdk_info['is_simulator'] = IsSimulator(target_cpu)
+  sdk_info['is_simulator'] = environment == 'simulator'
   sdk_info['macos_build'] = ExtractOSVersion()
   sdk_info['platform'] = platform
-  sdk_info['platform_name'] = GetPlaformDisplayName(target_cpu)
+  sdk_info['platform_name'] = GetPlaformDisplayName(environment)
   sdk_info['sdk'] = effective_sdk
   sdk_info['sdk_build'] = ExtractSDKInfo('build-version', effective_sdk)
   sdk_info['sdk_path'] = ExtractSDKInfo('path', effective_sdk)
@@ -124,6 +123,12 @@
       choices=('x86', 'x64', 'arm', 'arm64'),
       help='target cpu')
   parser.add_argument(
+      '-e',
+      '--target-environment',
+      default='simulator',
+      choices=('simulator', 'device'),
+      help='target environment')
+  parser.add_argument(
       '-s', '--sdk-version',
       help='version of the sdk')
   parser.add_argument(
@@ -140,9 +145,8 @@
   args = ParseArgs(argv)
 
   sdk_info = GetSDKInfoForCpu(
-      GetAppleCpuName(args.target_cpu),
-      args.sdk_version,
-      args.deployment_target)
+      GetAppleCpuName(args.target_cpu), args.target_environment,
+      args.sdk_version, args.deployment_target)
 
   if args.output == '-':
     sys.stdout.write(json.dumps(sdk_info))
diff --git a/examples/ios/build/config/ios/sdk_info.gni b/examples/ios/build/config/ios/sdk_info.gni
index 90b8631..c800253 100644
--- a/examples/ios/build/config/ios/sdk_info.gni
+++ b/examples/ios/build/config/ios/sdk_info.gni
@@ -8,6 +8,8 @@
                        [
                          "--target-cpu",
                          current_cpu,
+                         "--target-environment",
+                         target_environment,
                          "--deployment-target",
                          ios_deployment_target,
                        ],
diff --git a/examples/ios/build/config/ios/templates/ios_binary_bundle.gni b/examples/ios/build/config/ios/templates/ios_binary_bundle.gni
index 1a3d629..43ec355 100644
--- a/examples/ios/build/config/ios/templates/ios_binary_bundle.gni
+++ b/examples/ios/build/config/ios/templates/ios_binary_bundle.gni
@@ -117,5 +117,11 @@
     bundle_contents_dir = bundle_root_dir
     bundle_executable_dir = bundle_contents_dir
     bundle_resources_dir = bundle_contents_dir
+
+    xcode_extra_attributes = {
+      CODE_SIGN_IDENTITY = ""
+      CODE_SIGNING_REQUIRED = "NO"
+      CODE_SIGNING_ALLOWED = "NO"
+    }
   }
 }
diff --git a/examples/ios/build/toolchain/ios/BUILD.gn b/examples/ios/build/toolchain/ios/BUILD.gn
index 12d246b..b779720 100644
--- a/examples/ios/build/toolchain/ios/BUILD.gn
+++ b/examples/ios/build/toolchain/ios/BUILD.gn
@@ -23,6 +23,8 @@
                             [
                               "--target-cpu",
                               current_cpu,
+                              "--target-environment",
+                              target_environment,
                               "--deployment-target",
                               ios_deployment_target,
                             ],