Skip to content

Commit

Permalink
Add ability to package an iOS dynamic framework into a format Xcode c…
Browse files Browse the repository at this point in the history
…an consume (#928)
  • Loading branch information
mccorkill1 committed Dec 14, 2020
1 parent e2b1e1e commit 572aee2
Show file tree
Hide file tree
Showing 27 changed files with 2,052 additions and 2 deletions.
154 changes: 154 additions & 0 deletions apple/internal/aspects/swift_dynamic_framework_aspect.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Aspect implementation for Swift dynamic framework support."""

load(
"@build_bazel_rules_swift//swift:swift.bzl",
"SwiftInfo",
)

SwiftDynamicFrameworkInfo = provider(
fields = {
"module_name": "The module name for the single swift_library dependency.",
"swiftinterfaces": """
Dictionary of architecture to the generated swiftinterface file for that architecture.
""",
"swiftdocs": """
Dictionary of architecture to the generated swiftdoc file for that architecture.
""",
"generated_header": """
The generated Objective-C header for the single swift_library dependency.
""",
"swiftmodules": """
Dictionary of architecture to the generated swiftmodule file for that architecture.
""",
"modulemap": """
Generated modulemap for that architecture.
""",
},
doc = """
Provider that collects artifacts required to build a Swift-based dynamic framework.
""",
)

def _swift_target_for_dep(dep):
"""Returns the target for which the dependency was compiled.
This is really hacky, but there's no easy way to acquire the Apple CPU for which the target was
built. One option would be to let this aspect propagate transitively through deps and have
another provider that propagates the CPU, but the model there gets a bit more complicated to
follow. With this approach, we avoid propagating the aspect transitively as well.
This should be cleaned up when b/141931700 is fixed (adding support for ctx.rule.split_attr).
"""
for action in dep.actions:
if action.mnemonic == "SwiftCompile":
target_found = False
for arg in action.argv:
if target_found:
return arg
if arg == "-target":
target_found = True
fail("error: Expected at least one Swift compilation action for target {}.".format(dep.label))

def _swift_arch_for_dep(dep):
"""Returns the architecture for which the dependency was built."""
target = _swift_target_for_dep(dep)
return target.split("-", 1)[0]

def _modulemap_contents(module_name):
"""Returns the contents for the modulemap file for the framework."""
return """\
framework module {module_name} {{
header "{module_name}.h"
requires objc
}}
""".format(module_name = module_name)

def _swift_dynamic_framework_aspect_impl(target, ctx):
"""Aspect implementation for Swift dynamic framework support."""

if not hasattr(ctx.rule.attr, "deps"):
return []

swiftdeps = [x for x in ctx.rule.attr.deps if SwiftInfo in x]
ccinfos = [x for x in ctx.rule.attr.deps if CcInfo in x]
# If there are no Swift dependencies, return nothing.
if not swiftdeps:
return []

if len(swiftdeps) != len(ctx.rule.attr.deps):
fail(
"""\
error: Found a mix of swift_library and other rule dependencies. Swift dynamic frameworks expect a \
single swift_library dependency.\
""",
)

# Collect all relevant artifacts for Swift dynamic framework generation.
module_name = None
generated_header = None
swiftdocs = {}
swiftmodules = {}
modulemap_file = None
for dep in swiftdeps:
swiftinfo = dep[SwiftInfo]
module_name = swiftinfo.module_name
arch = _swift_arch_for_dep(dep)

swiftmodule = None
swiftdoc = None
for module in swiftinfo.transitive_modules.to_list():
if not module.swift:
continue
swiftmodule = module.swift.swiftmodule
swiftdoc = module.swift.swiftdoc

swiftdocs[arch] = swiftdoc
swiftmodules[arch] = swiftmodule
modulemap_file = ctx.actions.declare_file("{}_file.modulemap".format(module_name))
ctx.actions.write(modulemap_file, _modulemap_contents(module_name))

# Get the generated_header using the CcInfo provider
for dep in ccinfos:
headers = dep[CcInfo].compilation_context.headers.to_list()
if headers:
generated_header = headers.pop(0)

# Make sure that all dictionaries contain at least one module before returning the provider.
if all([module_name, generated_header, swiftdocs, swiftmodules, modulemap_file]):
return [
SwiftDynamicFrameworkInfo(
module_name = module_name,
generated_header = generated_header,
swiftdocs = swiftdocs,
swiftmodules = swiftmodules,
modulemap = modulemap_file,
),
]
else:
fail(
"""\
error: Could not find all required artifacts and information to build a Swift dynamic framework. \
Please file an issue with a reproducible error case.\
""",
)

swift_dynamic_framework_aspect = aspect(
implementation = _swift_dynamic_framework_aspect_impl,
doc = """
Aspect that collects Swift information to construct a dynamic framework that supports Swift.
""",
)
190 changes: 190 additions & 0 deletions apple/internal/ios_rules.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ load(
"@build_bazel_rules_apple//apple/internal/aspects:swift_static_framework_aspect.bzl",
"SwiftStaticFrameworkInfo",
)
load(
"@build_bazel_rules_apple//apple/internal/aspects:swift_dynamic_framework_aspect.bzl",
"SwiftDynamicFrameworkInfo",
)
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"IosAppClipBundleInfo",
Expand Down Expand Up @@ -899,6 +903,185 @@ def _ios_extension_impl(ctx):
),
] + processor_result.providers

def _ios_dynamic_framework_impl(ctx):
"""Experimental implementation of ios_dynamic_framework."""

binary_target = [deps for deps in ctx.attr.deps if deps.label.name.endswith("swift_runtime_linkopts")][0]
extra_linkopts = []
if ctx.attr.extension_safe:
extra_linkopts.append("-fapplication-extension")

link_result = linking_support.register_linking_action(
ctx,
extra_linkopts = extra_linkopts,
)
binary_artifact = link_result.binary_provider.binary
debug_outputs_provider = link_result.debug_outputs_provider

actions = ctx.actions
bin_root_path = ctx.bin_dir.path
bundle_id = ctx.attr.bundle_id
bundle_name, bundle_extension = bundling_support.bundle_full_name_from_rule_ctx(ctx)
entitlements = entitlements_support.entitlements(
entitlements_attr = getattr(ctx.attr, "entitlements", None),
entitlements_file = getattr(ctx.file, "entitlements", None),
)
executable_name = bundling_support.executable_name(ctx)
features = features_support.compute_enabled_features(
requested_features = ctx.features,
unsupported_features = ctx.disabled_features,
)
label = ctx.label
platform_prerequisites = platform_support.platform_prerequisites_from_rule_ctx(ctx)
predeclared_outputs = ctx.outputs
rule_descriptor = rule_support.rule_descriptor(ctx)
rule_executables = ctx.executable

signed_frameworks = []
if getattr(ctx.file, "provisioning_profile", None):
signed_frameworks = [
bundle_name + rule_descriptor.bundle_extension,
]

archive_for_embedding = outputs.archive_for_embedding(
actions = actions,
bundle_name = bundle_name,
bundle_extension = bundle_extension,
executable_name = executable_name,
label_name = label.name,
rule_descriptor = rule_descriptor,
platform_prerequisites = platform_prerequisites,
predeclared_outputs = predeclared_outputs,
)

processor_partials = [
partials.apple_bundle_info_partial(
actions = actions,
bundle_extension = bundle_extension,
bundle_id = bundle_id,
bundle_name = bundle_name,
executable_name = executable_name,
entitlements = entitlements,
label_name = label.name,
platform_prerequisites = platform_prerequisites,
predeclared_outputs = predeclared_outputs,
product_type = rule_descriptor.product_type,
),
partials.binary_partial(
actions = actions,
binary_artifact = binary_artifact,
executable_name = executable_name,
label_name = label.name,
),
partials.bitcode_symbols_partial(
actions = actions,
binary_artifact = binary_artifact,
debug_outputs_provider = debug_outputs_provider,
dependency_targets = ctx.attr.frameworks,
label_name = label.name,
platform_prerequisites = platform_prerequisites,
),
partials.clang_rt_dylibs_partial(
actions = actions,
binary_artifact = binary_artifact,
clangrttool = ctx.executable._clangrttool,
features = features,
label_name = label.name,
platform_prerequisites = platform_prerequisites,
),
partials.debug_symbols_partial(
actions = actions,
bin_root_path = bin_root_path,
bundle_extension = bundle_extension,
bundle_name = bundle_name,
debug_dependencies = ctx.attr.frameworks,
debug_outputs_provider = debug_outputs_provider,
dsym_info_plist_template = ctx.file._dsym_info_plist_template,
executable_name = executable_name,
platform_prerequisites = platform_prerequisites,
rule_label = label,
),
partials.embedded_bundles_partial(
frameworks = [archive_for_embedding],
embeddable_targets = ctx.attr.frameworks,
platform_prerequisites = platform_prerequisites,
signed_frameworks = depset(signed_frameworks),
),
partials.extension_safe_validation_partial(
is_extension_safe = ctx.attr.extension_safe,
rule_label = label,
targets_to_validate = ctx.attr.frameworks,
),
partials.framework_provider_partial(
actions = actions,
bin_root_path = bin_root_path,
binary_provider = link_result.binary_provider,
bundle_name = bundle_name,
rule_label = label,
),
partials.resources_partial(
actions = actions,
bundle_extension = bundle_extension,
bundle_id = bundle_id,
bundle_name = bundle_name,
environment_plist = ctx.file._environment_plist,
executable_name = executable_name,
launch_storyboard = None,
platform_prerequisites = platform_prerequisites,
plist_attrs = ["infoplists"],
rule_attrs = ctx.attr,
rule_descriptor = rule_descriptor,
rule_executables = rule_executables,
rule_label = label,
targets_to_avoid = ctx.attr.frameworks,
top_level_attrs = ["resources"],
version_keys_required = False,
),
partials.swift_dylibs_partial(
actions = actions,
binary_artifact = binary_artifact,
dependency_targets = ctx.attr.frameworks,
label_name = label.name,
platform_prerequisites = platform_prerequisites,
swift_stdlib_tool = ctx.executable._swift_stdlib_tool,
),
partials.swift_dynamic_framework_partial(
actions = actions,
bundle_name = bundle_name,
label_name = label.name,
swift_dynamic_framework_info = binary_target[SwiftDynamicFrameworkInfo],
),
]

processor_result = processor.process(
ctx = ctx,
actions = actions,
bundle_extension = bundle_extension,
bundle_name = bundle_name,
entitlements = entitlements,
executable_name = executable_name,
partials = processor_partials,
platform_prerequisites = platform_prerequisites,
predeclared_outputs = predeclared_outputs,
provisioning_profile = getattr(ctx.file, "provisioning_profile", None),
rule_descriptor = rule_descriptor,
rule_executables = rule_executables,
rule_label = label,
)

providers = processor_result.providers

return [
DefaultInfo(files = processor_result.output_files),
IosFrameworkBundleInfo(),
OutputGroupInfo(
**outputs.merge_output_groups(
link_result.output_groups,
processor_result.output_groups,
)
),
] + providers

def _ios_static_framework_impl(ctx):
"""Experimental implementation of ios_static_framework."""

Expand Down Expand Up @@ -1461,6 +1644,13 @@ ios_framework = rule_factory.create_apple_bundling_rule(
doc = "Builds and bundles an iOS Dynamic Framework.",
)

ios_dynamic_framework = rule_factory.create_apple_bundling_rule(
implementation = _ios_dynamic_framework_impl,
platform_type = "ios",
product_type = apple_product_type.framework,
doc = "Builds and bundles an iOS dynamic framework that is consumable by Xcode.",
)

ios_static_framework = rule_factory.create_apple_bundling_rule(
implementation = _ios_static_framework_impl,
platform_type = "ios",
Expand Down
5 changes: 5 additions & 0 deletions apple/internal/partials.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ load(
"@build_bazel_rules_apple//apple/internal/partials:swift_dylibs.bzl",
_swift_dylibs_partial = "swift_dylibs_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:swift_dynamic_framework.bzl",
_swift_dynamic_framework_partial = "swift_dynamic_framework_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:swift_static_framework.bzl",
_swift_static_framework_partial = "swift_static_framework_partial",
Expand Down Expand Up @@ -114,6 +118,7 @@ partials = struct(
settings_bundle_partial = _settings_bundle_partial,
static_framework_header_modulemap_partial = _static_framework_header_modulemap_partial,
swift_dylibs_partial = _swift_dylibs_partial,
swift_dynamic_framework_partial = _swift_dynamic_framework_partial,
swift_static_framework_partial = _swift_static_framework_partial,
watchos_stub_partial = _watchos_stub_partial,
)
Loading

0 comments on commit 572aee2

Please sign in to comment.